$(document).ready(function() {
	var label = new Label();

	var domObj = { 
			$window : $(window),
			$releasedDetailDiv : $("#releasedDetailDiv"),
			$releasedDetailGrd : $("#releasedDetailGrd"),
			$defectDetailDiv : $("#defectDetailDiv"),
			$defectDetailGrd : $("#defectDetailGrd"),
			$mtrlBoxDetailDiv : $("#mtrlBoxDetailDiv"),
			$retainBoxInfoDiv : $("#retainBoxInfoDiv"),
			$wipRetainInfoGrd : $("#wipRetainInfoGrd"),
			$wipRetainDetailInfoDiv : $("#wipRetainDetailInfoDiv"),
			$wipRetainDetailInfoGrd : $("#wipRetainDetailInfoGrd")
	};
	
    var VAL ={
        NORMAL     : "0000000"  ,
        T_XPBISPTH : "XPBISPTH" ,
        T_XPLSTEQP : "XPLSTEQP" ,
        T_XPAPLYWO : "XPAPLYWO" ,
        T_XPINQCOD : "XPINQCOD" ,
        T_XPINQBOX : "XPINQBOX" ,
        T_XPUNPACK : "XPUNPACK" ,
        T_XPMOVEOUT: "XPMOVEOUT",
        T_XPBISOPE : "XPBISOPE",
        T_XPBMDLDF : "XPBMDLDF",
        T_XPDEFECT : "XPDEFECT" ,
        T_XPWHSOPE : "XPWHSOPE" ,
        T_XPWIPRETAIN : "XPWIPRETAIN" ,
        T_XPSPCRET : "XPSPCRET",
        EVT_USER   : $("#userId").text(),
        SLOT_NO    : 0,
        SLOT_NO_INPUT:false,
        STD_QTY    : 0
    };
    var gDefectMap = {};//Get from DATA-DFCT
    var woInfo = {};//get woInfo
        gCrLayoutInfo = {
            layot_flg : null,
            layot_id : null,
            layotg_id : null,
            layot_dsc : null,
            x : null,
            y : null
        };

    /**
     * All controls's jquery object/text
     * @type {Object}
     */
    var controlsQuery = {
        W                   : $(window)                ,
        woTypeSelect        : $("#woTypeSelect")       ,
        woIDSelect          : $("#woIDSelect")         ,
        to_thicknessTxt     : $("#to_thicknessTxt")  ,
        opeSelect           : $("#opeSelect")          ,
        toolSelect          : $("#toolSelect")         ,
        layoutIdSelect      : $("#layoutIdSelect")     ,
        ppboxIdTxt          : $("#ppboxIdTxt")         ,
        ppboxTxt          : $("#ppboxTxt")         ,
        prdIDTxt            : $("#prdIDTxt")           ,
        slotIDTxt           : $("#slotIDTxt")          ,
        lotIdTxt            : $("#lotIdTxt")           ,
        okOutCrrTxt         : $("#okOutCrrTxt")        ,
        rawBoxStdQtyInput   : $("#rawBoxStdQtyInput")  ,
        rawCountInput       : $("#rawCountInput")      ,
        destShopSelect      : $("#destShopSelect")     ,
        print1Select      : $("#print1Select"),
        mainGrd   :{
            grdId     : $("#releasedDetailGrd")   ,
            grdPgText : "#releasedDetailPg"       ,
            fatherDiv : $("#releasedDetailDiv")
        },
        defectDetailGrid : {
            grdId     : $("#defectDetailGrd")   ,
            grdPgText : "#defectDetailPg"       ,
            fatherDiv : $("#defectDetailDiv")
        },
        mtrlBoxDetailGrid : {
        	grdId     : $("#mtrlBoxDetailGrd")   ,
            grdPgText : "#mtrlBoxDetailPg"
        }
    };

    /**
     * All button's jquery object
     * @type {Object}
     */
    var btnQuery = {
        f1                    : $("#f1_btn"),
        f2                    : $("#f2_btn"),
        f6                    : $("#f6_btn"),
        f8                    : $("#f8_btn"),
        f9_cancel_unpack      : $("#f9_cancel_unpack_btn"),
        okOutBtn              : $("#okOutBtn")           ,
        wip_retain_btn        : $("#wip_retain_btn"),
        wip_retain_cancel_btn : $("#wip_retain_cancel_btn"),
        testPrint             : $("#testPrint")
    };
    /**
     * All tool functions
     * @type {Object}
     */
    var toolFunc = {
      clearInput : function(){
            controlsQuery.ppboxIdTxt.val("");
            controlsQuery.ppboxTxt.val("");
            controlsQuery.prdIDTxt.val("");
            controlsQuery.slotIDTxt.val("");
            controlsQuery.okOutCrrTxt.val("");
            controlsQuery.lotIdTxt.val("");
            controlsQuery.to_thicknessTxt.val("");
        },
        setDestShopSel : function(){
        	var inObj;
        	var data_ext = "'C','D'";
        	var iary={
        		data_cate : 'DEST',
        		data_ext  : data_ext,
        		user_id   : VAL.EVT_USER
        	};
        	inObj = {
			   trx_id     : 'XPLSTDAT' ,
	           action_flg : 'F'        ,
	           iary       : iary
        	};
        	DestoutObj = comTrxSubSendPostJson(inObj);
        	if(DestoutObj.rtn_code == VAL.NORMAL){
        		_setSelectDate(DestoutObj.tbl_cnt,DestoutObj.oary,"data_id","data_desc","#destShopSelect",true);
        	}
        },
        /**
         * Set data for select
         * @param Data count
         * @param Data array
         * @param Property name
         * @param Target select control's jquery object
         */
        setSelectDate : function(dataCnt, arr, selVal, queryObj){
            var i, realCnt;

            queryObj.empty();
            realCnt = parseInt( dataCnt, 10);

            if( realCnt == 1 ){
                if( arr.hasOwnProperty(selVal)){
                    queryObj.append("<option value="+ arr[selVal] +">"+ arr[selVal] +"</option>");
                }
            }else if( realCnt > 1 ){
                for( i = 0; i < realCnt; i++ ){
                    if( arr[i].hasOwnProperty(selVal)){
                        queryObj.append("<option value="+ arr[i][selVal] +">"+ arr[i][selVal] +"</option>");
                    }
                }
            }
            queryObj.select2({
            	theme : "bootstrap"
            });
        },
        setSwhPathDate : function(dataCnt, arr, selVal, selVal2,selVal3,queryObj){
            var i, realCnt;

            queryObj.empty();
            realCnt = parseInt( dataCnt, 10);

            if( realCnt == 1 ){
                queryObj.append("<option value="+ arr[selVal] + "@" + arr[selVal2]+">"+ arr[selVal3] +"</option>");
            }else if( realCnt > 1 ){
                for( i = 0; i < realCnt; i++ ){
                    queryObj.append("<option value="+ arr[i][selVal] + "@" + arr[i][selVal2] +">"+ arr[i][selVal3] +"</option>");
                }
            }
        },
        setOpeSelectDate : function(dataCnt, arr, selVal, selVal2, selVal3, selTxt, queryObj){
            var i, realCnt;

            queryObj.empty();
            realCnt = parseInt( dataCnt, 10);

            if( realCnt == 1 ){
                queryObj.append("<option value="+ arr[selVal] + "@" + arr[selVal2] + "@" + arr[selVal3] +">"+ arr[selTxt] +"</option>");
            }else if( realCnt > 1 ){
                for( i = 0; i < realCnt; i++ ){
                    queryObj.append("<option value="+ arr[i][selVal] + "@" + arr[i][selVal2] + "@" + arr[i][selVal3] +">"+ arr[i][selTxt] +"</option>");
                }
            }
        },
        iniWoTypeSelect : function(){
            setSelectObjValueTxtByData("#woTypeSelect","WOAB","data_id","data_desc");
        },
        iniOpeSelect : function(){
            var inObj, outObj;
            var user_id = VAL.EVT_USER;
            var iaryB = {
                user_id     : user_id
            };
            inObj = {
                trx_id      : VAL.T_XPBISOPE,
                action_flg  : 'I',
                iaryB       : iaryB
            };
            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                _setOpeSelectDate(outObj.tbl_cnt, outObj.oary, "ope_id", "ope_ver", "ope_dsc", controlsQuery.opeSelect);
//                _setOpeSelectDate(outObj.tbl_cnt, outObj.oary, "ope_id", "ope_ver", "ope_dsc", "#opeSelect",false);
                
            }
        },
        /**
         * 根据6300参数BXPR获取站点箱号限制规则. By ZJH
         * */
        getBxpr : function () {
            var outObj;
            var inObj = {
                trx_id : "XPLSTDAT",
                action_flg : "Q",
                iary : {
                    data_cate : "BXPR"
                }
            };
            outObj = comTrxSubSendPostJson(inObj);
            if(outObj.rtn_code === VAL.NORMAL){
                console.log(outObj);
                return outObj.oary;
            }else {
                console.log("未找到BXPR");
                return false;
            }
        },
        getBxlm : function () {
            var outObj;
            var inObj = {
                trx_id : "XPLSTDAT",
                action_flg : "Q",
                iary : {
                    data_cate : "BXLM"
                }
            };
            outObj = comTrxSubSendPostJson(inObj);
            if(outObj.rtn_code === VAL.NORMAL){
                console.log(outObj);
                return outObj.oary;
            }else {
                console.log("未找到BXLM");
                return false;
            }
        },
        /**
         * 根据站点，人员，机台的关系；筛选出可以使用的机台.
         * @returns {Boolean}
         * @author CMJ
         */
        iniToolSelect : function(){
            var inObj, outObj, ope_id, ope_ver, opeIndex;

            if(!$.trim(controlsQuery.opeSelect.val())){
                return false;
            }

            opeIndex = controlsQuery.opeSelect.val().indexOf("@");
            ope_id = controlsQuery.opeSelect.val().substr(0, opeIndex);
            ope_ver = controlsQuery.opeSelect.val().substr(opeIndex+1);

            if(!ope_id){
                console.error(ope_id);
                return false;
            }

            if(!ope_ver){
                console.error(ope_ver);
                return false;
            }

            inObj = {
                    trx_id      : VAL.T_XPLSTEQP,
                    action_flg  : 'F'           ,
                    ope_id      : ope_id        ,
                    ope_ver     : ope_ver       ,
                    user_id     : VAL.EVT_USER  
                };
            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                _setSelectDate(outObj.tbl_cnt, outObj.oary, "tool_id", "tool_id", "#toolSelect", false);
            }
        },
        getBoxInfo : function(box_id){
            var inObj,
                outObj;
            inObj = {
                trx_id      : VAL.T_XPINQBOX,
                action_flg  : 'X'           ,
                box_id      : box_id
            };
            outObj = comTrxSubSendPostJson(inObj);
            if(outObj.rtn_code == VAL.NORMAL){
                return outObj;
            }else{
                return null;
            }
        },
        getBoxAllPrdInfo : function(box_id){
            var inObj,
                outObj;
            inObj = {
                trx_id      : VAL.T_XPINQBOX,
                action_flg  : 'P'           ,
                order_slot_flg : 'Y'        ,
                box_id      : box_id        ,
                first_ope_id : 'Y'
            };
            outObj = comTrxSubSendPostJson(inObj);
            if(outObj.rtn_code == VAL.NORMAL){
                return outObj;
            }else{
                return null;
            }
        },
        getRetBoxInfoByBox : function(box_id){
            var inObj,
                outObj;
            inObj = {
                trx_id      : VAL.T_XPINQBOX,
                action_flg  : 'T'           ,
                box_id      : box_id
            };
            outObj = comTrxSubSendPostJson(inObj);
            if(outObj.rtn_code == VAL.NORMAL){
                return outObj.ret_box;
            }else{
                return null;
            }
        },
        
        crrInputKeyDownFnc : function (_okOutCrrTxt){
            var boxInfo,
            prdAry = [];
        	controlsQuery.mainGrd.grdId.jqGrid("clearGridData");
            var box_id = $.trim(_okOutCrrTxt.val());
            /**
             * bxpr         :   6300bxpr参数
             * data_desc    :   站点描述
             * data_ext     :   站点信息
             * data_id      :   制程代码
             * ext_1        :   箱号头
             * bxlm         :   6300BXLM参数 站点是否启用箱号的限制
             * */
            var currOpe_info = $.trim(controlsQuery.opeSelect.val());   //当前选择的ope_info
            var currOpe_info_arr = currOpe_info.split("@");
            var currData_ext = currOpe_info_arr[0];                     //当前选择的站点信息
            var bxpr = toolFunc.getBxpr();                              //获取BXPR参数配置表
            var bxlm = toolFunc.getBxlm();                              //获取站点是否开启限制
            var arr = new Array();                                      //当前站点与BXPR参数配置站点一致的信息(可能一个站点允许多个箱号种类)
            var limitInfo = new Array();                                //当前站点与BXLM参数配置一致的信息
            var boxHead;
            var isLimit = true;
            if(bxlm){
                for(var i = 0;i<bxlm.length;i++) {
                    if (currData_ext == bxlm[i].data_ext) {
                        limitInfo.push(bxlm[i]);
                    }
                }
                console.log(limitInfo);
                if(limitInfo.length>1){
                    showErrorDialog("","BXLM参数错误,站点信息重复!");
                    clearOutBoxInput();
                    return false;
                }else if(limitInfo.length<1){
                    showErrorDialog("","请现在6300 BXLM中先添加此站点的信息");
                    clearOutBoxInput();
                    return false;
                }
                if(limitInfo[0].ext_1 === "Y"){
                    isLimit = true;
                }
                if(limitInfo[0].ext_1 === "N"){
                    isLimit = false;
                }
            }else {
                showErrorDialog("","获取参数BXLM失败!");
                return false;
            }
            console.info("bxpr:"+bxpr);
            if(bxpr){
                for(var i = 0;i<bxpr.length;i++) {
                    if (currData_ext == bxpr[i].data_ext) {
                        arr.push(bxpr[i]);
                    }
                }
            }else{
                showErrorDialog("","获取参数BXPR失败!");
                clearOutBoxInput();
                return false;
            }
            console.log("arr:"+arr);
            if((limitInfo[0].ext_1 === "N")){
                if(_okOutCrrTxt.val()){
                    boxInfo = toolFunc.getBoxAllPrdInfo(_okOutCrrTxt.val());
                    if(boxInfo){
                        if(boxInfo.box_cnt == 0){
                            showErrorDialog("","箱子["+_okOutCrrTxt.val()+"]不存在，请确认!");
                            _okOutCrrTxt.val("");
                            clearOutBoxInput();
                            return false;
                        }
                        VAL.STD_QTY = boxInfo.std_qty;
                        if(0 < parseInt(boxInfo.prd_qty, 10)){
                            if(1 == parseInt(boxInfo.prd_qty, 10)){
                                prdAry.push(boxInfo.table);
                            }else{
                                prdAry = boxInfo.table;
                            }

                            if(boxInfo.first_ope_id == prdAry[0].cr_ope_id_fk &&
                                "INPR" == prdAry[0].prd_stat){
                                for(var i=0;i<prdAry.length;i++){
                                    oary = prdAry[i];

                                    if(oary.prd_admin_flg !== "" ){
                                        if(oary.prd_admin_flg.substring(2,3) === "Y"){
                                            prdAry[i].th_judge_flg = "<button class='thCss'>NG</button>";
                                        }else {
                                            prdAry[i].th_judge_flg = "<button class='thCss'>OK</button>";
                                        }

                                        if(oary.prd_admin_flg.substring(3,4) === "Y"){
                                            prdAry[i].fz_flg = "<button class='fzCss'>NG</button>";
                                        }else {
                                            prdAry[i].fz_flg = "<button class='fzCss'>OK</button>";
                                        }
                                    }
                                    prdAry[i].cus_id=boxInfo.cus_id_fk;

                                }

                                setGridInfo(prdAry, "#releasedDetailGrd");
                                toolFunc.enhanceGrid();
                                //                        _okOutCrrTxt.attr({"disabled":true});
//                            _okOutCrrTxt[0].disabled = true;

                            }else{
                                _okOutCrrTxt.val("");
                                showErrorDialog("","只能输入工艺线路首站点未出账的箱子或者空箱子！");
                                clearOutBoxInput();
                                return false;
                            }
                        }
                    }
                }else{
                    _okOutCrrTxt.val("");
                }
                //_okOutCrrTxt.attr({"disabled":true});
                // console.info("disabled");
                return false;
            }
            if(arr.length!=0 && (limitInfo[0].ext_1 === "Y")){
                for(var i=0;i<arr.length;i++){
                    if(box_id.indexOf(arr[i].ext_1)===0){
                    // if((arr[i].ext_2!="Y") || (arr[i].ext_2==="Y" && box_id.indexOf(arr[i].ext_1)===0) ){
                        if(_okOutCrrTxt.val()){
                            boxInfo = toolFunc.getBoxAllPrdInfo(_okOutCrrTxt.val());
                            if(boxInfo){
                                if(boxInfo.box_cnt == 0){
                                    showErrorDialog("","箱子["+_okOutCrrTxt.val()+"]不存在，请确认!");
                                    _okOutCrrTxt.val("");
                                    clearOutBoxInput();
                                    return false;
                                }
                                VAL.STD_QTY = boxInfo.std_qty;
                                if(0 < parseInt(boxInfo.prd_qty, 10)){
                                    if(1 == parseInt(boxInfo.prd_qty, 10)){
                                        prdAry.push(boxInfo.table);
                                    }else{
                                        prdAry = boxInfo.table;
                                    }

                                    if(boxInfo.first_ope_id == prdAry[0].cr_ope_id_fk &&
                                        "INPR" == prdAry[0].prd_stat){
                                        for(var i=0;i<prdAry.length;i++){
                                            oary = prdAry[i];

                                            if(oary.prd_admin_flg !== "" ){
                                                if(oary.prd_admin_flg.substring(2,3) === "Y"){
                                                    prdAry[i].th_judge_flg = "<button class='thCss'>NG</button>";
                                                }else {
                                                    prdAry[i].th_judge_flg = "<button class='thCss'>OK</button>";
                                                }

                                                if(oary.prd_admin_flg.substring(3,4) === "Y"){
                                                    prdAry[i].fz_flg = "<button class='fzCss'>NG</button>";
                                                }else {
                                                    prdAry[i].fz_flg = "<button class='fzCss'>OK</button>";
                                                }
                                            }
                                            prdAry[i].cus_id=boxInfo.cus_id_fk;

                                        }

                                        setGridInfo(prdAry, "#releasedDetailGrd");
                                        toolFunc.enhanceGrid();
                                        //                        _okOutCrrTxt.attr({"disabled":true});
//                            _okOutCrrTxt[0].disabled = true;

                                    }else{
                                        _okOutCrrTxt.val("");
                                        showErrorDialog("","只能输入工艺线路首站点未出账的箱子或者空箱子！");
                                        clearOutBoxInput();
                                        return false;
                                    }
                                }
                            }
                        }else{
                            _okOutCrrTxt.val("");
                        }
                        //_okOutCrrTxt.attr({"disabled":true});
                        // console.info("disabled");
                        return false;
                    }
                }
                showErrorDialog("","当前站点:["+currData_ext+"]不能使用:["+box_id+"]!");
                clearOutBoxInput();
                return false;
            }else{
                showErrorDialog("","当前站点:["+currData_ext+"]未设置限制箱号的种类");
                clearOutBoxInput();
                return false;
            }

//             if(_okOutCrrTxt.val()){
//                 boxInfo = toolFunc.getBoxAllPrdInfo(_okOutCrrTxt.val());
//                 if(boxInfo){
//                 	if(boxInfo.box_cnt == 0){
//                         showErrorDialog("","箱子["+_okOutCrrTxt.val()+"]不存在，请确认!");
//                         _okOutCrrTxt.val("");
//                         clearOutBoxInput();
//                         return false;
//                 	}
//                 	VAL.STD_QTY = boxInfo.std_qty;
//                     if(0 < parseInt(boxInfo.prd_qty, 10)){
//                         if(1 == parseInt(boxInfo.prd_qty, 10)){
//                             prdAry.push(boxInfo.table);
//                         }else{
//                             prdAry = boxInfo.table;
//                         }
//
//                         if(boxInfo.first_ope_id == prdAry[0].cr_ope_id_fk &&
//                             "INPR" == prdAry[0].prd_stat){
//                         	for(var i=0;i<prdAry.length;i++){
//                         		oary = prdAry[i];
//
//                         		if(oary.prd_admin_flg !== "" ){
//                         			if(oary.prd_admin_flg.substring(2,3) === "Y"){
//                         				prdAry[i].th_judge_flg = "<button class='thCss'>NG</button>";
//                             		}else {
//                             			prdAry[i].th_judge_flg = "<button class='thCss'>OK</button>";
//                             		}
//
//                             		if(oary.prd_admin_flg.substring(3,4) === "Y"){
//                             			prdAry[i].fz_flg = "<button class='fzCss'>NG</button>";
//                             		}else {
//                             			prdAry[i].fz_flg = "<button class='fzCss'>OK</button>";
//                             		}
//                         		}
//                         		prdAry[i].cus_id=boxInfo.cus_id_fk;
//
//                         	}
//
//                             setGridInfo(prdAry, "#releasedDetailGrd");
//                             toolFunc.enhanceGrid();
//     //                        _okOutCrrTxt.attr({"disabled":true});
// //                            _okOutCrrTxt[0].disabled = true;
//
//                         }else{
//                             _okOutCrrTxt.val("");
//                             showErrorDialog("","只能输入工艺线路首站点未出账的箱子或者空箱子！");
//                            clearOutBoxInput();
//                             return false;
//                         }
//                     }
//                 }
//             }else{
//             	_okOutCrrTxt.val("");
//             }
//             //_okOutCrrTxt.attr({"disabled":true});
//            // console.info("disabled");
//             return false;
        },
        
        woIDSelectChangeFnc : function(){
            var i,
                iary,
                inTrxObj,
                outTrxObj,
                oary,
                wo_id,
                layoutGOary = [],
                layoutInfoA = [],
                layoutCnt;

            wo_id = $("#woIDSelect").val();
            if(!wo_id){
                return false;
            }

            iary = {
                wo_id : wo_id
            };
            inTrxObj ={
              trx_id     : "XPLAYOUT",
              action_flg : "W", 
              iary       : iary,
              bind_so_flg: "Y",
              tbl_cnt    : 1
            };

            outTrxObj = comTrxSubSendPostJson(inTrxObj);
            if( outTrxObj.rtn_code == VAL.NORMAL ) {
              oary = outTrxObj.oary;
              if(oary==null){
                showErrorDialog("003","版式信息异常,请检查产品对应的版式信息");
                return false;
              }

              if("G" === oary.layot_flg){
                  //Layout group
                  layoutCnt = parse11Int(oary.tbl_cnt_b, 10);
                  if(1 === layoutCnt){
                      layoutGOary.push(oary.oaryB);
                  }else if(1 < layoutCnt){
                      layoutGOary = oary.oaryB;
                  }else{
                      console.error("获取tbl_cnt_b异常 [%s]", layoutCnt);
                      return false;
                  }

                  for( i = 0; i < layoutCnt; i++ ){
                      layoutInfoA.push({
                          layot_flg : oary.layot_flg,
                          layot_id : layoutGOary[i].layot_id_fk,
                          layotg_id : layoutGOary[i].layotg_id_fk,
                          layot_dsc : layoutGOary[i].layot_dsc,
                          x : layoutGOary[i].x_axis,
                          y : layoutGOary[i].y_axis
                      });
                  }
              }else if("S" === oary.layot_flg){
                  //Single layout
                  layoutInfoA.push({
                      layot_flg : oary.layot_flg,
                      layot_id : oary.layot_id,
                      layotg_id : "",
                      layot_dsc : oary.layot_dsc,
                      x : oary.x_axis_cnt,
                      y : oary.y_axis_cnt
                  });
              }else{
                  console.error("获取layot_flg异常 [%s]", oary.layot_flg);
                  return false;
              }

              toolFunc.updateLayoutInfo(layoutInfoA);
              toolFunc.getWoInfoFunc();
            }else if(outTrxObj.rtn_code=="1002106"){
        	controlsQuery.layoutIdSelect.empty();  	
        }
        },
        getWoInfoFunc : function(){
            var wo_id,
                inObj,
                outObj;

            controlsQuery.to_thicknessTxt.val("");
            wo_id = controlsQuery.woIDSelect.val().trim();
            if(!wo_id){
                console.warn("wo_id [%s] is null!", wo_id);
                return false;
            }

            inObj = {
                trx_id      : VAL.T_XPAPLYWO,
                action_flg  : 'Q'           ,
                tbl_cnt     : 1             ,
                get_first_ope : 'Y',
                iary : {
                    wo_id     : wo_id,
                    mtrl_cate : "SHMT"
                }
            };
            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                controlsQuery.to_thicknessTxt.val(outObj.oary.to_thickness);
                woInfo = outObj;
                console.log(woInfo);
//                var ope_info = outObj.oary.first_ope_id+"@00000";
//                controlsQuery.opeSelect.val(ope_info);
            }
            return true;
        },
        getMtrlBoxInfoFunc2 : function(mtrl_box_id){
            var wo_id,
                inObj,
                outObj;

            wo_id = controlsQuery.woIDSelect.val().trim();
            if(!wo_id){
                console.warn("wo_id [%s] is null!", wo_id);
                return false;
            }

            if(!mtrl_box_id){
                console.warn("getMtrlBoxInfoFunc2 mtrl_box_id [%s] is null!", mtrl_box_id);
                return false;
            }

            inObj = {
                trx_id      : VAL.T_XPUNPACK,
                action_flg  : 'M'           ,
                wo_id       : wo_id         ,
                mtrl_box_id : mtrl_box_id
            };
            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                return outObj.ret_prd_in;
            }
            return false;
        },
        updateLayoutInfo : function(layoutInfoA){
            var i,
                layoutCnt = layoutInfoA.length,
                selHtml = "";

            //Set select
            controlsQuery.layoutIdSelect.empty();
            for( i = 0; i < layoutCnt; i++ ){
                selHtml += "<option value=" +
                    layoutInfoA[i]['layot_flg'] + "@" +
                    layoutInfoA[i]['layot_id'] + "@" +
                    layoutInfoA[i]['layotg_id'] + "@" +
                    layoutInfoA[i]['x'] + "@" +
                    layoutInfoA[i]['y'] + "@" +
                    layoutInfoA[i]['layot_dsc'] +">"+ layoutInfoA[i]['layot_id'] +"</option>";
            }
            controlsQuery.layoutIdSelect.append(selHtml);
            controlsQuery.layoutIdSelect.select2({theme : "bootstrap"});
            toolFunc.syncLayoutInfo();
        },
        /**
         * 同步当前选中的layout的信息
         */
        syncLayoutInfo : function(){
            var selectedLayoutVal,
                selectedLayoutValAry;

            //Get current layout info (first in select)
            selectedLayoutVal = controlsQuery.layoutIdSelect.val().trim();
            if(!selectedLayoutVal){
                return false;
            }

            selectedLayoutValAry = selectedLayoutVal.split("@");
            gCrLayoutInfo = {
                layot_flg : selectedLayoutValAry[0],
                layot_id : selectedLayoutValAry[1],
                layotg_id : selectedLayoutValAry[2],
                layot_dsc : selectedLayoutValAry[5],
                x : parseInt(selectedLayoutValAry[3], 10),
                y : parseInt(selectedLayoutValAry[4], 10)
            };

            if(!gCrLayoutInfo.layot_id ||
                !gCrLayoutInfo.x ||
                !gCrLayoutInfo.y){
                showErrorDialog("","版式图[" + gCrLayoutInfo.layot_id +
                    "]设定异常: x[" + gCrLayoutInfo.x +
                    "], y[" + gCrLayoutInfo.y + "]");
                return false;
            }

            console.log("Current layout is %s", gCrLayoutInfo.layot_id);
            return true;
        },
        //Get all defect in DATA-DFCT ==> gDefectMap
        get_all_defect_func : function(){
            var i,
                defectCnt,
                inTrxObj,
                outTrxObj,
                dataAry = [];

            inTrxObj = {
                trx_id: VAL.T_XPINQCOD,
                action_flg: 'I',
                data_cate : 'DFCT'
            };
            outTrxObj = comTrxSubSendPostJson(inTrxObj);
            if( outTrxObj.rtn_code == VAL.NORMAL) {
                gDefectMap = {};
                defectCnt = parseInt(outTrxObj.tbl_cnt, 10);
                if( 1 === defectCnt){
                    dataAry.push(outTrxObj.oary);
                }else{
                    dataAry = outTrxObj.oary;
                }
                for( i = 0; i < defectCnt; i++ ){
                    gDefectMap[ dataAry[i].data_id ] = {
                        defDsc : dataAry[i].data_ext
                    };
                }
            }
        },
        /**
         *
         * @param prd_seq_id
         * @returns []
         */
        getDefectListByPrdSeqId : function(prd_seq_id,jugeflag){
            var inObj,
                outObj,
                def_cnt,
                actionflg,
                defList = [],
                prd_jge_info = { };

            if(jugeflag == "Y"){
                actionflg = 'q';
            }else{
                actionflg = 'Q';
            }

            inObj = {
                trx_id      : VAL.T_XPDEFECT,
                action_flg  : actionflg           ,
                prd_seq_id  : prd_seq_id
            };
            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                def_cnt = parseInt( outObj.def_cnt, 10 );
                if(1 === def_cnt){
                    defList.push( outObj.defList );
                }else if(1 < def_cnt){
                    defList = outObj.defList;
                }

                //Get other property in [DATA-DFCT]
                // => defectAry
                $.each(defList, function( index, value ) {
                    var defectMap,
                        tmpDefCode = value.defect_code;

                    defectMap = gDefectMap;
                    if( defectMap.hasOwnProperty(tmpDefCode) ){
                        value.defDsc = defectMap[tmpDefCode].defDsc;
                    }else{
                        value.defDsc = tmpDefCode;
                        console.error("Defect [%d] in prd [%d] not define in [DATE-DFCT]!", tmpDefCode, prd_seq_id);
                    }
                });

                prd_jge_info.defList = defList;
                prd_jge_info.prd_grade = outObj.prd_grade;
                prd_jge_info.new_logic_flg = outObj.new_logic_flg;
//                prd_jge_info.prd_seq_grd = outObj.prd_seq_grd;
                prd_jge_info.prd_seq_grd_t = outObj.prd_seq_grd_t;
                prd_jge_info.prd_seq_grd_c = outObj.prd_seq_grd_c;
            }

            return prd_jge_info;
        },
        //By sht show defect detail info
        showDefectDetail : function(id){
            var rowData,
                prd_seq_id,
                defList;

            rowData = controlsQuery.mainGrd.grdId.jqGrid("getRowData", id);
            prd_seq_id = rowData['prd_seq_id'];

            defList = (this.getDefectListByPrdSeqId(prd_seq_id)).defList;
            setGridInfo(defList, controlsQuery.defectDetailGrid.grdId);

            return true;
        },
        /**
         * 行点击事件
         * @param id 行号
         */
        enhanceGridByID : function(id){
            var jBtnHtml,
                jBtnId,
                dBtnHtml,
                dBtnId;

            //judge button
            jBtnId = "judgeBtn_" + id;
            jBtnHtml = "<button id=" + jBtnId + ">点击</button>";

            //defect_detail button
            dBtnId = "defectDetailBtn_" + id;
            dBtnHtml = "<button id=" + dBtnId + ">明细</button>";

            //Set grid
            controlsQuery.mainGrd.grdId.jqGrid('setRowData', id, {
                judge: jBtnHtml,
                defect_detail: dBtnHtml
            });

            //Bind action
            $("#" + dBtnId).click(function(){
                toolFunc.showDefectDetail(id);
                return false;
            });
            $("#" + jBtnId).click( toolFunc.showDefectDialog );
        },
        enhanceGrid : function(){
            var i,
                ids,
                idLen;
            ids = controlsQuery.mainGrd.grdId.jqGrid('getDataIDs');
            idLen = ids.length;
            for( i=0; i < idLen; i++){
                toolFunc.enhanceGridByID(ids[i]);
            }
        },
        showDefectDialog : function(){
            console.log("Click row %s",  this.id.substr(9));
            var rowData,
                rowId,
                proc_id,
                wo_id,
                prd_seq_id,
                group_id,
                x_axis_cnt,
                y_axis_cnt,
                oldDefList,
                old_judge_grade,
                prd_jge_info = { },
                new_logic_flg,
                prd_seq_grd_t,
                prd_seq_grd_c,
                rm_flg,
                cus_id,
                showDefList = [];

            wo_id = controlsQuery.woIDSelect.val().trim();
            if(!wo_id){
                showErrorDialog("","请选择内部订单号！");
                return false;
            }

            rowId      = this.id.substr(9);
            rowData    = controlsQuery.mainGrd.grdId.jqGrid("getRowData", rowId);
            prd_seq_id = rowData['prd_seq_id'];
            group_id   = rowData['group_id'];
            x_axis_cnt = rowData['x_axis_cnt_fk'];
            y_axis_cnt = rowData['y_axis_cnt_fk'];
            rm_flg     = false;
            cus_id     = rowData['cus_id'];
            if(cus_id=="007"){
            	rm_flg = true;
            }
            proc_id = "JBIC";
            prd_jge_info = toolFunc.getDefectListByPrdSeqId(prd_seq_id,"Y");
            oldDefList = prd_jge_info.defList;
            for(var i=0; i<oldDefList.length; i++){
            	if(oldDefList[i].show_flg == "Y"){
            		showDefList.push(oldDefList[i]);
            	}
            }
            old_judge_grade = prd_jge_info.prd_grade;
            new_logic_flg = prd_jge_info.new_logic_flg;
//            prd_seq_grd = prd_jge_info.prd_seq_grd;
            prd_seq_grd_t = prd_jge_info.prd_seq_grd_t;
            prd_seq_grd_c = prd_jge_info.prd_seq_grd_c;
    
            $(this)._showDefectJudgeDialog({
                prd_seq_id    : prd_seq_id,
                group_id      : group_id,
                cus_id        : cus_id,
                proc_id       : proc_id,
                rowId         : rowId,
                pep_lvl       : "1",
                wo_id         : wo_id,
                x_axis_cnt    : x_axis_cnt,
                y_axis_cnt    : y_axis_cnt,
                oldDefList    : oldDefList,
                showDefList   : showDefList,
                judge_grade   : old_judge_grade,
                new_logic_flg : new_logic_flg,
//                prd_seq_grd   : prd_seq_grd, 
                prd_seq_grd_t   : prd_seq_grd_t,
                prd_seq_grd_c   : prd_seq_grd_c,
                rm_flg        : rm_flg,
                groupFlg      : true,
                ds_recipe_id  : rowData.ds_recipe_id,
                callbackFn : function(data) {
                    var prd_seq_id,
                        rowId,
                        judge_grade,
                        own_typ,
                        remark,
                        groupId,
                        defectAry,
                        inObj,
                        outObj;

                    if(data){
                        prd_seq_id  = data.prd_seq_id;
                        rowId       = data.rowId;
                        judge_grade = data.judge_grade;
                        own_typ     = data.own_typ;
                        defectAry   = data.defectAry;
                        remark      = data.remark;
                        groupId     = data.group_id;
                        
                        inObj = {
                            trx_id         : VAL.T_XPDEFECT     ,
                            action_flg     : "N"                ,
                            prd_seq_id     : prd_seq_id         ,
                            judge_grade    : judge_grade        ,
                            own_typ        : own_typ        ,
                            pv_judge_grade : judge_grade        ,
                            def_cnt        : defectAry.length   ,
                            evt_user       : VAL.EVT_USER       ,
                            defList        : defectAry
                        };
                        if(remark){
                        	inObj.remark = remark;
                        }else{
                        	remark = "";
                        }
                        if(groupId){
                        	inObj.group_id = groupId;
                        }else{
                        	groupId="";
                        }
                        outObj = comTrxSubSendPostJson(inObj);
                        if (outObj.rtn_code == VAL.NORMAL) {
                            setGridInfo(defectAry, controlsQuery.defectDetailGrid.grdId);
                            controlsQuery.mainGrd.grdId.jqGrid("setRowData",rowId,{ds_recipe_id:remark});
                            controlsQuery.mainGrd.grdId.jqGrid("setRowData",rowId,{group_id:groupId});
                    		if(cus_id=="068"&&judge_grade=="S"){
                    			$("#spcDialog_reportBtn").showCallBackWarnningDialog({
                					errMsg : "玻璃: ["+prd_seq_id+"]等级为S，请取消释放",
                					callbackFn : function(data) {
                						if (data.result == true) {
                					        var prd_seq_id,
                			                inObj,
                			                outObj,
                			                selectRow;

                			                selectRow = controlsQuery.mainGrd.grdId.jqGrid("getRowData", rowId);
                			                prd_seq_id = selectRow['prd_seq_id'];

                			                inObj = {
                			                    trx_id         : VAL.T_XPUNPACK     ,
                			                    action_flg     : "C"                ,
                			                    prd_seq_id     : prd_seq_id         ,
                			                    evt_usr        : VAL.EVT_USER
                			                };
                			                outObj = comTrxSubSendPostJson(inObj);
                			                if (outObj.rtn_code == VAL.NORMAL) {
                			                    controlsQuery.mainGrd.grdId.jqGrid('delRowData', rowId);
                			                    controlsQuery.to_thicknessTxt.val(outObj.to_thickness);
                			                }else{
                			                    return false;
                			                }
                				        }else {
                				        	return false;
                				        }						
                					}	        		
                	        	});
                    		}
                            toolFunc.showDefectDetail(rowId);
                        }
                    }
                    return false;
                }
            });
            return false;
        },
    };
    btnQuery.testPrint.bind('click',testPrint);

    function testPrint() {
        label.PrintYNKLCD(controlsQuery.print1Select.find("option:selected").text(),"11111,11111,11111,111,1,1111");
    }

    //获取打印机
    function getPrinters(){
        controlsQuery.print1Select.append("<option ></option>");
        if (printers !== undefined) {
            for(var i=0; i<printers.length; i++){
                controlsQuery.print1Select.append("<option>"+ printers[i] +"</option>");
            }
        }
    }
    getPrinters();
    /**
     * All button click function
     * @type {Object}
     */
    var btnFunc = {
        //Query wo
    	/**
    	 * 增加：根据站点筛选出可以显示的内部订单。By CMJ
    	 * @author CMJ
    	 */
        f1_func : function(){
            var woType,
                wostat,
                inObj,
                outObj;
            var opeIndex,ope_id,ope_ver;
            woType = controlsQuery.woTypeSelect.val();
            /**
             * 站点为空时，没有对应可以操作的内部订单。By CMJ
             */
            if(!$.trim(controlsQuery.opeSelect.val())){
                return false;
            }
            
            opeIndex = controlsQuery.opeSelect.val().indexOf("@");
            ope_id = controlsQuery.opeSelect.val().substr(0, opeIndex);
            ope_ver = controlsQuery.opeSelect.val().substr(opeIndex+1);
            if(!woType){
//                console.error("current work order type [%s] is invalid!", woType);
                return false;
            }

            inObj = {
                trx_id      : VAL.T_XPAPLYWO,
                action_flg  : 'L'           ,
                iary : {
                    wo_cate : woType,
                    wo_stat : "WAIT",
                    ope_id  : ope_id,
                    ope_ver : ope_ver
                }
            };

            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
            	if(outObj.tbl_cnt == 0){
            		showErrorDialog("","查询无记录");
            	}
        		toolFunc.setSelectDate(outObj.tbl_cnt, outObj.oary, "wo_id", controlsQuery.woIDSelect);
        		toolFunc.woIDSelectChangeFnc();
            }
        },
        
        f2_func : function(){
            'use strict';
            var inTrxObj,
                box_id,
                ppbox,
                box_std_qty,
                raw_count,
                inWoTrxObj,
                outWoTrxObj,
                wo_pln_prd_qty,
                wo_rsv_pln_prd_qty,
                wo_rsv_dps_qty,
                wo_rsv_snd_dps_qty,
                wo_rsv_trd_dps_qty,
                lchkflg;
//                wo_act_dps_qty,
//                wo_act_snd_dps_qty,
//                wo_act_trd_dps_qty,
                

           var vdr_id = woInfo.oary.cus_id_fk;
           var mtrl_type = "SHMT";
            var dest_shop = $.trim(controlsQuery.destShopSelect.val());
           var wo_id = $.trim(controlsQuery.woIDSelect.val());
           var raw_count = $.trim(controlsQuery.rawCountInput.val());    //数量
/*            var raw_weight = $.trim(controlsQuery.rawWeightInput.val());
            var thickness = $.trim(controlsQuery.thicknessTxt.val());*/
          /*  var vdr_box_id =  $.trim(controlsQuery.mtrlBoxInput.val());*/
            box_std_qty =  $.trim(controlsQuery.rawBoxStdQtyInput.val()); //来料箱子格位数

           if( !vdr_id ){showErrorDialog("","此工单没有客户代码！"); return false;}
           /*      if( !mtrl_type ){showErrorDialog("","请选择来料型号！"); return false;}*/
            if( !dest_shop ){showErrorDialog("","请选择仓位！"); return false;}
           if( !wo_id ){showErrorDialog("","请选择内部订单号！"); return false;}
            
            box_id = $.trim(controlsQuery.ppboxIdTxt.val());
            if( !box_id ){
            	btnFunc.autoCreateBoxFunc();
            	box_id = $.trim(controlsQuery.ppboxIdTxt.val());
            }
            ppbox = $.trim(controlsQuery.ppboxTxt.val());
           // if( !ppbox ){showErrorDialog("","请输入来料箱体！"); return false;}
/*            if (!vdr_box_id){
            	vdr_box_id = box_id;
            }*/
            
            if( !box_std_qty){showErrorDialog("","请输入箱子的子格位数！"); return false;}
            box_std_qty = parseInt(box_std_qty, 10);
            if(isNaN(box_std_qty)){
                showErrorDialog("","请输入正确的子格位数！");
                return false;
            }
            if(box_std_qty <=0){
                showErrorDialog("","子格位数不能为0！");
                return false;
            }
            if( !raw_count ){showErrorDialog("","请输入数量！"); return false;}
            raw_count = parseInt(raw_count, 10);
            if(isNaN(raw_count)){
                showErrorDialog("","请输入正确的数量！");
                return false;
            }
            if(raw_count <=0){
                showErrorDialog("","数量不能为0！");
                return false;
            }

            if(box_std_qty < raw_count){
                showErrorDialog("","子格位数不能小于箱子中产品数量！");
                return false;
            }
            /*         if(raw_weight){ //有输入才检查
                if( parseFloat(raw_weight) >= 0) {
                    raw_weight = parseFloat(raw_weight);
                }else{
                    showErrorDialog("","来料毛重数值不正确，请输入正确数字！");
                    return false;
                }
            }

           stdFromThickness = toolFunc.getWoStdFromThickness();
            stdFromThickness = parseFloat(stdFromThickness);
            controlsQuery.stdThicknessTxt.val(stdFromThickness);

            if (mtrl_type != VAL.woMtrl_Prod_ID){showErrorDialog("","当前所选来料型号["+mtrl_type+"]和内部订单来料型号["+VAL.woMtrl_Prod_ID+"]不符"); return false;}

            if(thickness){ //有输入才检查
                if( parseFloat(thickness) >= 0) {
                    thickness = parseFloat(thickness);
                }else{
                    showErrorDialog("","产品厚度数值不正确，请输入正确数字！");
                    return false;
                }

                if( 0 != stdFromThickness &&
                    thickness != stdFromThickness){
                    showErrorDialog("","内部订单绑定的产品厚度["+ stdFromThickness +"]和输入值["+ thickness +"]不符！！");
                    return false;
                }
            }*/
            //Query WO info
            inWoTrxObj = {
                trx_id      : VAL.T_XPAPLYWO,
                action_flg  : 'Q'           ,
                tbl_cnt     : 1             ,
                iary : {
                    wo_id     : wo_id
                }
            };
            outWoTrxObj = comTrxSubSendPostJson(inWoTrxObj);
            if (outWoTrxObj.rtn_code == VAL.NORMAL) {
                if( parseInt( outWoTrxObj.tbl_cnt,10 ) >0 ){
                    if( outWoTrxObj.hasOwnProperty("oary")){
                    	lchkflg = 0;
                    	wo_rsv_pln_prd_qty = parseInt(outWoTrxObj.oary.rsv_pln_prd_qty, 10);
                    	wo_pln_prd_qty = parseInt(outWoTrxObj.oary.pln_prd_qty, 10);
                        if ( parseInt((wo_pln_prd_qty + parseInt(raw_count,10)),10) > wo_rsv_pln_prd_qty ) {
                        	lchkflg = 1;
                        }
                        if(lchkflg == 1){
                        	showErrorDialog("",
                              "内部订单[" + wo_id +
                                  "]此笔来料后实际来料数量[" + parseInt((wo_pln_prd_qty + parseInt(raw_count,10)),10) +
                                  "]大于计划来料数量[" + wo_rsv_pln_prd_qty + "]"
                          );
                          return false;
                      }
                    }
                }
            }  
            inTrxObj = {
                trx_id     : VAL.T_XPWHSOPE,
                action_flg : 'A',
                evt_user   : VAL.EVT_USER,
                box_cnt    : 1 ,
                wo_id      : wo_id,
                iary :  {
                    vdr_id    : vdr_id,
                    box_id    : box_id,
                    mtrl_type : mtrl_type,
                    dest_shop : dest_shop,
                    wo_id     : wo_id,
                    ppbox     : ppbox,
                    diffCnt   : raw_count,
                    vdr_box_id: box_id,
                    box_std_qty : box_std_qty,
                    weight    :  0
                }
            };

            //Query WO info

            var outObj = comTrxSubSendPostJson(inTrxObj);
            if(outObj.rtn_code == VAL.NORMAL){
            var iary = {
            		 wo_id : wo_id,
                     box_id : box_id
            }
            var inTrxObj = {
                    trx_id     : VAL.T_XPWHSOPE,
                    action_flg : 'B',
                    evt_user   : VAL.EVT_USER,//发料人员改为登陆人员
                    relate_usr : VAL.EVT_USER,
                    box_cnt    : 1,
                    iary       : iary
                };
                //WAIT -> WFRL
                var outTrxObj = comTrxSubSendPostJson(inTrxObj);
                if(outTrxObj.rtn_code == VAL.NORMAL){
                	showMessengerSuccessDialog("登记成功!!",1);
                }
            }
            return true;
        },
        
        //Release panel
        f6_func : function(){
            "use strict";
            var tool_id,
                wo_id,
                mtrl_box_id,
                prd_seq_id,
                slot_id,
                box_id,
                prd_thickness,
                ret_box,
                iary,
                inTrxObj,
                outTrxObj,
                oary;

            controlsQuery.prdIDTxt.blur();//防止重复敲回车

            tool_id = controlsQuery.toolSelect.val();
            wo_id = controlsQuery.woIDSelect.val();
            mtrl_box_id = $.trim(controlsQuery.ppboxIdTxt.val());
            prd_seq_id = $.trim(controlsQuery.prdIDTxt.val());
            prd_thickness = controlsQuery.to_thicknessTxt.val().trim();
            slot_id = controlsQuery.slotIDTxt.val().trim();
            if(!$("#layoutIdSelect").val()){
            	showErrorDialog("","请选择板式名称");
                return false;
            }

            if( !wo_id ){
                showErrorDialog("","请选择内部订单号");
                return false;
            }
            if( !mtrl_box_id ){
                showErrorDialog("","请输入来料箱号");
                return false;
            }
            if( !prd_seq_id ){
				showErrorDialog("","请输入产品ID!",function(){$("#prdIDTxt").focus();});
				return false;
			}


            //Get box info
            //判断是否是扫码枪扫码
            var mean = meanFunc(oneKeyTimeArr)
            if(mean<spanTime){
                isScanner = true;
                $("#okOutCrrTxt").attr("readonly","readonly");
            }
            console.log(mean+"  "+oneKeyTimeArr);
            oneKeyTimeArr = [];
            if(isScanner){
                box_id = controlsQuery.okOutCrrTxt.val();
            }else{
                showErrorDialog("","请使用扫码枪扫码!");
                clearOutBoxInput();
                return false;
            }
            if( !box_id ){
                showErrorDialog("","请输入要转入的箱号！");
                return false;
            }
            if( !prd_thickness ){
                showErrorDialog("","请绑定产品厚度");
                return false;
            }
     

        iary = {
            wo_id : wo_id
        };
        inTrxObj ={
          trx_id     : "XPLAYOUT",
          action_flg : "W",
          iary       : iary,
          tbl_cnt    : 1
        };

        outTrxObj = comTrxSubSendPostJson(inTrxObj);

        if( outTrxObj.rtn_code != VAL.NORMAL ) {
          return false;
        }    
        else if( outTrxObj.rtn_code == VAL.NORMAL ) {
          oary = outTrxObj.oary;
          if(oary==null){
            showErrorDialog("003","版式信息异常,请检查产品对应的版式信息");
            return false;
          }            
        }    
            //获取箱子信息
            ret_box = toolFunc.getBoxInfo(box_id);
            if(ret_box){
            	if(ret_box.bnk_flg == "3"){
                    btnQuery.f6.showCallBackWarnningDialog({
                    	errMsg : "箱子" + box_id + "是在制保留箱，确定是否继续释放?",
                        callbackFn : function(data) {
                    	   if(data.result){
                    		   

                    		   inTrxObj = {
                          			trx_id     : "XPUNPACK",
                          			action_flg : "X",
                          			prd_seq_id : prd_seq_id,
                          			wo_id      : wo_id,
                          			box_id     : mtrl_box_id,
                          			out_chk_flg:"Y"
                          		};
                          		outTrxObj = comTrxSubSendPostJson(inTrxObj);
                          		if(outTrxObj.rtn_code === VAL.NORMAL){
                          			if(outTrxObj.has_custom_material_flg === "N"){
                          				  btnQuery.f6.showCallBackWarnningDialog({
                                            	errMsg : "此片玻璃不存在于来料数据中,是否继续投产",
                                               callbackFn : function(data) {
                                            	    if(data.result){
                                              			if(outTrxObj.out_control_flg === "Y"){
                                            				  btnQuery.f6.showCallBackWarnningDialog({
                                                              	errMsg : "此片玻璃编码不符合产品设定，是否继续投产",
                                                                 callbackFn : function(data) {
                                                              	    if(data.result){
                                                              		    btnFunc.relase_func(prd_seq_id,box_id,mtrl_box_id,tool_id,wo_id,prd_thickness,slot_id);
                                                              	    }
                                                                  }
                                                              });
                                            			}else{
                                            				btnFunc.relase_func(prd_seq_id,box_id,mtrl_box_id,tool_id,wo_id,prd_thickness,slot_id);
                                            			}                                            	    }
                                                }
                                            });
                          			}else{
                              			if(outTrxObj.out_control_flg === "Y"){
                            				  btnQuery.f6.showCallBackWarnningDialog({
                                              	errMsg : "此片玻璃编码不符合产品设定，是否继续投产",
                                                 callbackFn : function(data) {
                                              	    if(data.result){
                                              		    btnFunc.relase_func(prd_seq_id,box_id,mtrl_box_id,tool_id,wo_id,prd_thickness,slot_id);
                                              	    }
                                                  }
                                              });
                            			}else{
                            				btnFunc.relase_func(prd_seq_id,box_id,mtrl_box_id,tool_id,wo_id,prd_thickness,slot_id);
                            			}                          			}
                          		}
                              		
//                    		   btnFunc.relase_func(prd_seq_id,box_id,mtrl_box_id,tool_id,wo_id,prd_thickness,slot_id,group_id);
                    	   }
                        }
                    });
                    return;
            	}else{
            		 inTrxObj = {
                   			trx_id     : "XPUNPACK",
                   			action_flg : "X",
                   			prd_seq_id : prd_seq_id,
                   			wo_id      : wo_id,
                   			box_id     : mtrl_box_id,
                   			out_chk_flg:"Y"
                   		};
                   		outTrxObj = comTrxSubSendPostJson(inTrxObj);
                   		if(outTrxObj.rtn_code === VAL.NORMAL){
                   			if(outTrxObj.has_custom_material_flg === "N"){
                   				  btnQuery.f6.showCallBackWarnningDialog({
                                     	errMsg : "此片玻璃不存在于来料数据中,是否继续投产",
                                        callbackFn : function(data) {
                                     	    if(data.result){
                                      			if(outTrxObj.out_control_flg === "Y"){
                                    				  btnQuery.f6.showCallBackWarnningDialog({
                                                      	errMsg : "此片玻璃编码不符合产品设定，是否继续投产",
                                                         callbackFn : function(data) {
                                                      	    if(data.result){
                                                      		    btnFunc.relase_func(prd_seq_id,box_id,mtrl_box_id,tool_id,wo_id,prd_thickness,slot_id);
                                                      	    }
                                                          }
                                                      });
                                    			}else{
                                    				btnFunc.relase_func(prd_seq_id,box_id,mtrl_box_id,tool_id,wo_id,prd_thickness,slot_id);
                                    			}                                     	    }
                                         }
                                     });
                   			}else{
                      			if(outTrxObj.out_control_flg === "Y"){
                    				  btnQuery.f6.showCallBackWarnningDialog({
                                      	errMsg : "此片玻璃编码不符合产品设定，是否继续投产",
                                         callbackFn : function(data) {
                                      	    if(data.result){
                                      		    btnFunc.relase_func(prd_seq_id,box_id,mtrl_box_id,tool_id,wo_id,prd_thickness,slot_id);
                                      	    }
                                          }
                                      });
                    			}else{
                    				btnFunc.relase_func(prd_seq_id,box_id,mtrl_box_id,tool_id,wo_id,prd_thickness,slot_id);
                    			}                   			}
                   		}
//            		btnFunc.relase_func(prd_seq_id,box_id,mtrl_box_id,tool_id,wo_id,prd_thickness,slot_id);
            	}
            }
            return false;
        },
        relase_func :function(prd_seq_id,box_id,mtrl_box_id,tool_id,wo_id,prd_thickness,slot_id){
        	var inObj,
        		outObj,
        		rand_row_id,
        		auto_move_out_cnt = 25;
            inObj = {
                trx_id         : VAL.T_XPUNPACK     ,
                action_flg     : "U"                ,
                prd_seq_id     : prd_seq_id         ,
                box_id         : box_id             ,
                mtrl_box_id    : mtrl_box_id        ,
                tool_id        : tool_id            ,
                wo_id          : wo_id              ,
                thickness      : prd_thickness      ,
                layot_id       : gCrLayoutInfo.layot_id ,
                x_axis_cnt     : gCrLayoutInfo.x    ,
                y_axis_cnt     : gCrLayoutInfo.y    ,
                evt_usr        : VAL.EVT_USER       
            };

            //User input slot
            if(slot_id){
                slot_id = parseInt(slot_id, 10);
                VAL.SLOT_NO_INPUT = true;
                VAL.SLOT_NO = slot_id; 
                if(isNaN(slot_id)){
                    showErrorDialog("","请输入正确的子格位，必须为数字！");
                    return false;
                }

                if(slot_id <= 0){
                    showErrorDialog("","请输入正确的子格位，必须为正数！");
                    return false;
                }

                inObj.slot_no = slot_id;
            }

            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
        		if(outObj.prd_admin_flg !== "" ){
        			if(outObj.prd_admin_flg.substring(2,3) === "Y"){
        				outObj.th_judge_flg = "<button class='thCss'>NG</button>";
            		}else {
            			outObj.th_judge_flg = "<button class='thCss'>OK</button>";
            		}
            		
            		if(outObj.prd_admin_flg.substring(3,4) === "Y"){
            			outObj.fz_flg = "<button class='fzCss'>NG</button>";
            		}else {
            			outObj.fz_flg = "<button class='fzCss'>OK</button>";
            		}
        		}
        		

                rand_row_id = $.jgrid.randId();
                controlsQuery.mainGrd.grdId.jqGrid('addRowData', rand_row_id, outObj, "first");
                toolFunc.enhanceGridByID(rand_row_id);
                controlsQuery.prdIDTxt.val("");
                if (VAL.SLOT_NO_INPUT && (parseInt(slot_id,10) < parseInt(VAL.STD_QTY,10))){
                	controlsQuery.slotIDTxt.val(parseInt(VAL.SLOT_NO,10) + 1);
                }else {
                	controlsQuery.slotIDTxt.val("");
                }
                controlsQuery.to_thicknessTxt.val(outObj.to_thickness);
                controlsQuery.prdIDTxt.focus();

//                if(auto_move_out_cnt === parseInt(outObj.box_prd_qty, 10)){
//                    showWarnningDialog({
//                        errMsg  : '箱子[' + box_id + ']已经释放' + auto_move_out_cnt + '片，是否提配？',
//                        callbackFn : function(data) {
//                            if(data.result === true){
//                                console.log('Auto move out %s', box_id);
//                                btnQuery.f8.click();
//                            }
//                        }
//                    });
//                }
            }else {
            	VAL.SLOT_NO_INPUT = false;
            	return false;
            }
        },
        //Unpack
        f8_func : function(){
            "use strict";
            var wo_id,
                outBoxId,
                tool_id,
                lot_id,//提示显示的lot_id
                lot_id_fk,//绑定的lot_id
                prd_qty,
                ret_box,
                swh_out_ope_info,
                swh_out_ope_info_ary,
                mtrlBoxAry = [],
                iary,
                inTrxObj,
                outTrxObj,
                oary;

            wo_id = $.trim(controlsQuery.woIDSelect.val());
            if(!wo_id){
                showErrorDialog('','请选择内部订单！');
                return false;
            }

            tool_id = controlsQuery.toolSelect.val();   
        	//Get box info
            outBoxId = controlsQuery.okOutCrrTxt.val();
            if( !outBoxId ){
                showErrorDialog("","请输入要出账的箱号！");
                clearOutBoxInput();
                return false;
            }
            //获取箱子信息
            ret_box = toolFunc.getBoxInfo(outBoxId);
            if(ret_box.wo_id_fk != wo_id){
                showErrorDialog('','当前选中内部订单[' + wo_id +
                    ']和箱子所属内部订单不一致[' + ret_box.wo_id_fk + ']');
                clearOutBoxInput();
                return false;
            }

            iary = {
                    wo_id : wo_id
                };
                inTrxObj ={
                  trx_id     : "XPLAYOUT",
                  action_flg : "W",
                  iary       : iary,
                  tbl_cnt    : 1
                };

                outTrxObj = comTrxSubSendPostJson(inTrxObj);

                if( outTrxObj.rtn_code != VAL.NORMAL ) {
                    return false;
                }    
                else if( outTrxObj.rtn_code == VAL.NORMAL ) {
                  oary = outTrxObj.oary;
                  if(oary==null){
                    showErrorDialog("003","版式信息异常,请检查产品对应的版式信息");
                    return false;
                  }            
                }    

        	var mtrlBoxQty = parseInt(ret_box.oary3_cnt, 10);
            if(ret_box){
                if(0 < mtrlBoxQty){
                    if(1 == mtrlBoxQty){
                    	mtrlBoxAry.push(ret_box.oary3);
                    }else{
                    	mtrlBoxAry = ret_box.oary3;
                    }
                }else{
                    showErrorDialog("","箱子中没有可提配的产品！");
                    clearOutBoxInput();
                	return false;
                }
            }else{
                clearOutBoxInput();
            	return false;
            }
//            var inObjchk = {
//                    trx_id     : VAL.T_XPMOVEOUT ,
//                    manual_flg : "Y"             ,
//                    tool_id    : tool_id         ,
//                    box_id     : outBoxId        ,
//                    evt_usr    : VAL.EVT_USER    ,
//                    gchk_flg   : "C"
//                };
//            var outObjchk = comTrxSubSendPostJson(inObjchk,"N");
//            if( outObjchk.rtn_code != VAL.NORMAL ) {
//            	 if( outObjchk.rtn_code == "123" ){
//            	 }else{
//            		 showErrorDialog(outObjchk.rtn_code,outObjchk.rtn_mesg); 
//                    return false;
//            	 }
//            } 
            prd_qty = ret_box.prd_qty;

            if(prd_qty > 0){                        
               //F12产品提配
                var msg = "本次提配数量为[" + prd_qty + "],产品来自["
                + mtrlBoxQty +"]个来料箱。";
                for(var i=0;i<mtrlBoxQty;i++){
                	if(mtrlBoxAry[i].w_flg == "Y"){
                		msg = msg + "来料箱["+ mtrlBoxAry[i].mtrl_box_id+"]剩余["+ mtrlBoxAry[i].prd_cat_qty+"]片,";
                	}
                }
                msg = msg + "是否提配?";
                btnQuery.f8.showCallBackWarnningDialog({
                	errMsg : msg,
                    callbackFn : function(data) {
                	   if(data.result){
                           //Get lot id
                           lot_id = $.trim(controlsQuery.lotIdTxt.val());
                          // var lot_id_sb= lot_id.split("-")[1];
                          // var lot_id_sp = lot_id.split("-");
                          // var lot_id_sb = lot_id_sp[1];
                          //  console.log("split:"+lot_id.split("-"));
                          //  console.log("lot_id_sp:"+lot_id_sp);

                           if(ret_box.cr_lot_flg == "Y"){//箱子中有空批次的产品，需生成批次
                        	   if(ret_box.bnk_flg != "3"){
									if(!lot_id){//批次为空
										lot_id = btnFunc.autoCreateLotIdFunc();
									}
									if(ret_box.lot_id_fk == "MIX"){
										lot_id = "MIX";
									}else{
										lot_id = $.trim(controlsQuery.lotIdTxt.val());
									}
									lot_id_fk = $.trim(controlsQuery.lotIdTxt.val());
                        	   }else{
                        		   controlsQuery.lotIdTxt.val("");
                        	   }                          	
                           }else{//无需生成批次
	                           	lot_id = ret_box.lot_id_fk;
	                           	$.trim(controlsQuery.lotIdTxt.val(lot_id));
                           }

                           
                           var inObj = {
                               trx_id     : VAL.T_XPMOVEOUT ,
                               manual_flg : "Y"             ,
                               tool_id    : tool_id         ,
                               box_id     : outBoxId        ,
                               evt_usr    : VAL.EVT_USER    ,
                               gchk_flg   : "N"
                           };
                           if(lot_id_fk){
                        	   inObj.lot_id = lot_id_fk;
                           }
                           var outObj = comTrxSubSendPostJson(inObj);
                           var lot_id_sp = lot_id.split("-");
                           var lot_id_sb = lot_id_sp[1];
                           // console.log("split:"+lot_id.split("-"));
                           // console.log("lot_id_sp:"+lot_id_sp);
                           // console.log(lot_id);
                           // console.log(lot_id_sb);
                           // console.log(lot_id_fk);

                           if (outObj.rtn_code == VAL.NORMAL) {
                               try{
	                               controlsQuery.lotIdTxt.val("");
	                                //  label.PrintBacth(lot_id);//print

	                               //label.PrintLabelForBox(lot_id);
                                   //打印流程单
                                   //2.工单
                                   var woId  = $.trim(controlsQuery.woIDSelect.val());
                                   if (woId) {
                                       iary.wo_id = woId;
                                   }
                                   var  inObj2 = {
                                       trx_id : 'XPAPLYWO',
                                       action_flg : 'Q',
                                       tbl_cnt : 1,
                                       iary : iary
                                   };

                                   var outObj2 = comTrxSubSendPostJson(inObj2);
                                   if(outObj2.rtn_code == VAL.NORMAL){
                                       //客户订单
                                       var so_id = outObj2.oary.so_id;
                                       var from_thickness;
                                       var to_thickness;
                                       var iary2={
                                           wo_id : so_id
                                       };
                                       var inObj4 = {
                                           trx_id : 'XPAPLYSO',
                                           action_flg : 'Q',
                                           tbl_cnt : 1,
                                           iary : iary2
                                       };
                                       var outObj4 = comTrxSubSendPostJson(inObj4);
                                       if(outObj4.rtn_code == VAL.NORMAL){
                                            from_thickness  = outObj4.oary.from_thickness;
                                            to_thickness = outObj4.oary.to_thickness;
                                       }
                                       //3.工单计划数量
                                       var planQty = outObj2.oary.pln_prd_qty;
                                       //属性 AB
                                       var mtrlCateFk = outObj2.oary.mdl_cate_fk;
                                       var inObj3 = {
                                           trx_id : "XPLSTDAT",
                                           action_flg : "Q",
                                           iary : {
                                               data_cate : "MDCT",
                                               data_id : mtrlCateFk
                                           }
                                       };
                                       var outObj3 = comTrxSubSendPostJson(inObj3);
                                       var mtrlCate =  outObj3.oary.data_desc;
                                        var woCateDsc = outObj2.oary.woCateDsc;  // 量产或者实验
                                       //4.机种 不知道
                                        var jz =outObj2.oary.mtrl_size ;   // 换成  产品尺寸
                                       //5.客户代码
                                       var cusId = outObj2.oary.cus_id_fk;
                                       //6.未减薄料号
                                       var fmMdlIdFk =  outObj2.oary.mtrl_prod_id_fk;
                                       //7.减薄后料号
                                       var thMdlIdFk = outObj2.oary.th_mdl_id_fk;
                                       //8.数量  箱子里的数量
                                       var prdQty =  ret_box.prd_qty;
                                       //9.包装箱号
                                       var boxId = ret_box.box_id;
                                       //10.箱号 (来料箱号)
                                       var mtrlBoxId;
                                       if(isArray(ret_box.oary3)){
                                           mtrlBoxId =  ret_box.oary3[0].mtrl_box_id;
                                       }else{
                                           mtrlBoxId = ret_box.oary3.mtrl_box_id;
                                       }

                                       //11.投料日期
                                       var crtTimestamp = outObj2.oary.crt_timestamp;
                                       //12.基板型态 + 板厚
                                       if("006"==outObj2.oary.cus_id_fk||"007"==outObj2.oary.cus_id_fk){

                                           var mdlGuige = outObj2.oary.mdl_guige+" "+from_thickness +"-><<" +to_thickness;
                                           console.log("006and007_mdlGuige:"+mdlGuige);

                                           //13.排版数
                                           var layoutIdFk = outObj2.oary.layout_id_fk;
                                           console.log("006and007_layoutIdFk:"+layoutIdFk);
                                       }else {
                                           //12.基板型态 + 板厚
                                           var mdlGuige = outObj2.oary.spec+" "+from_thickness +"->" +to_thickness;
                                           console.log("Not006and007_mdlGuige:"+mdlGuige);
                                           //13.排版数
                                           var layoutIdFk = outObj2.oary.layoutId;
                                           var oldBox = outObj2.oary.oldBox;
                                           console.log("Not006and007_layoutIdFk:"+layoutIdFk);
                                       }
                                       var prdList = ret_box.table;
                                       var prdId = [];
                                       var prdId1 = [];
                                           for(var i = 0 ; i < prdList.length; i++){
                                              if(i<=19){
                                                  prdId.push(prdList[i].prd_seq_id);
                                              }else{
                                                  prdId1.push(prdList[i].prd_seq_id);
                                              }
                                           }

                                       // var printObj = {
                                       //     lot_id : lot_id_sb,
                                       //     woId : woId,
                                       //     planQty : planQty,
                                       //     mtrlCate : mtrlCate,
                                       //     jz : jz,
                                       //     cusId : cusId,
                                       //     fmMdlIdFk : fmMdlIdFk,
                                       //     thMdlIdFk : thMdlIdFk,
                                       //     prdQty : prdQty,
                                       //     boxId : boxId,
                                       //     mtrlBoxId : mtrlBoxId,
                                       //     crtTimestamp : crtTimestamp,
                                       //     mdlGuige : mdlGuige,
                                       //     layoutIdFk : layoutIdFk,
                                       //     prdId : prdId
                                       // }

                                       var printObj = {
                                           lot_id : lot_id, //加工批号
                                           woId : woId,    //工单ID
                                           planQty : planQty,  //计划数量
                                           mtrlCate : mtrlCate,  //属性
                                           woCateDsc : woCateDsc,//工单类型
                                           jz : jz,           //机种取消并改为玻璃尺寸
                                           cusId : cusId,  //客户代码
                                           fmMdlIdFk : fmMdlIdFk,  //未减薄料号
                                           thMdlIdFk : thMdlIdFk,  //减薄后料号
                                           prdQty : prdQty,   //玻璃数量
                                           boxId : boxId,   //包装箱号
                                           mtrlBoxId : mtrlBoxId,  //来料箱号
                                           crtTimestamp : crtTimestamp,  //投料日期
                                           mdlGuige : mdlGuige,   //基板型态
                                           layoutIdFk : layoutIdFk,   //排版数
                                           oldBox :oldBox,     // 是否原箱返
                                           prdId : prdId   //玻璃ID
                                       }
                                       var printObj1 = {
                                           lot_id : lot_id+"(2)", //加工批号
                                           woId : woId,    //工单ID
                                           planQty : planQty,  //计划数量
                                           mtrlCate : mtrlCate,  //属性
                                           woCateDsc : woCateDsc,//工单类型
                                           jz : jz,           //机种取消并改为玻璃尺寸
                                           cusId : cusId,  //客户代码
                                           fmMdlIdFk : fmMdlIdFk,  //未减薄料号
                                           thMdlIdFk : thMdlIdFk,  //减薄后料号
                                           prdQty : prdQty,   //玻璃数量
                                           boxId : boxId,   //包装箱号
                                           mtrlBoxId : mtrlBoxId,  //来料箱号
                                           crtTimestamp : crtTimestamp,  //投料日期
                                           mdlGuige : mdlGuige,   //基板型态
                                           layoutIdFk : layoutIdFk,   //排版数
                                           oldBox :oldBox,     // 是否原箱返
                                           prdId : prdId1   //玻璃ID
                                       }



                                       var printObj2 = {
                                           lot_id : lot_id_sb,
                                           woId : woId,
                                           planQty : planQty,
                                           mtrlCate : mtrlCate,
                                           jz : jz,
                                           cusId : cusId,
                                           fmMdlIdFk : fmMdlIdFk,
                                           thMdlIdFk : thMdlIdFk,
                                           prdQty : prdQty,
                                           boxId : boxId,
                                           mtrlBoxId : mtrlBoxId,
                                           crtTimestamp : crtTimestamp,
                                           mdlGuige : mdlGuige,
                                           layoutIdFk : layoutIdFk
                                       }

                                       try{
                                           if("007"==cusId ||"006"==cusId){
                                               if(prdQty<=20){
                                                   label.PrintYNKLCD(controlsQuery.print1Select.find("option:selected").text(),JSON.stringify(printObj));
                                               }else {
                                                   label.PrintYNKLCD(controlsQuery.print1Select.find("option:selected").text(),JSON.stringify(printObj));
                                                   label.PrintYNKLCD(controlsQuery.print1Select.find("option:selected").text(),JSON.stringify(printObj1));
                                               }
                                               label.PrintYNKLCD(controlsQuery.print1Select.find("option:selected").text(),JSON.stringify(printObj));
                                           }else {
                                               if(prdQty<=20){
                                                   label.PrintForYNKHN(controlsQuery.print1Select.find("option:selected").text(),JSON.stringify(printObj));
                                               }else {
                                                   label.PrintForYNKHN(controlsQuery.print1Select.find("option:selected").text(),JSON.stringify(printObj));
                                                   label.PrintForYNKHN(controlsQuery.print1Select.find("option:selected").text(),JSON.stringify(printObj1));
                                               }
                                           }
                                       }catch(ex){
                                           showMessengerErrorDialog("打印失败!",1);
                                           console.error(ex);
                                       }

                                       //镀膜才打印
                                       if(outObj2.oary.mdl_cate_fk.indexOf("B") != -1){// !=-1含有 ==-1不含有
                                           try{
                                               label.PrintYNKLCD2(controlsQuery.print1Select.find("option:selected").text(),JSON.stringify(printObj2));
                                           }catch(ex){
                                               showMessengerErrorDialog("打印失败!",1);
                                               console.error(ex);
                                           }
                                       }
                                   }
                                   showSuccessDialog(outBoxId + "提配成功,批次号为" + lot_id);
                                   clearOutBoxInput();
                                   controlsQuery.mainGrd.grdId.jqGrid("clearGridData");
                        	   }catch(ex){
                        		   console.error(ex);
                        	   }
                           }else{
                        	   controlsQuery.lotIdTxt.val("");
                           }
                	   }else{
                		   controlsQuery.lotIdTxt.val("");
                	   }
                    }
                });
            }else{
                showErrorDialog("","箱子中没有可提配的产品！");
                clearOutBoxInput();
                return false;
            }
        },
        //Cancel unpack
        f9_cancel_unpack_func : function(){
            var prd_seq_id,
                inObj,
                outObj,
                iRow,
                selectRowIds,
                selectRowIdsLen,
                selectRow;

            selectRowIds = controlsQuery.mainGrd.grdId.jqGrid('getGridParam','selarrrow');
            selectRowIdsLen = selectRowIds.length;
            if(selectRowIdsLen <= 0){
                showErrorDialog("","请选择要删除的记录！");
                return false;
            }
            for( iRow = selectRowIdsLen-1; iRow>=0; iRow--){
                selectRow = controlsQuery.mainGrd.grdId.jqGrid("getRowData", selectRowIds[iRow]);
                prd_seq_id = selectRow['prd_seq_id'];

                inObj = {
                    trx_id         : VAL.T_XPUNPACK     ,
                    action_flg     : "C"                ,
                    prd_seq_id     : prd_seq_id         ,
                    evt_usr        : VAL.EVT_USER
                };
                outObj = comTrxSubSendPostJson(inObj);
                if (outObj.rtn_code == VAL.NORMAL) {
                    controlsQuery.mainGrd.grdId.jqGrid('delRowData', selectRowIds[iRow]);
                    controlsQuery.to_thicknessTxt.val(outObj.to_thickness);
                }else{
                    return false;
                }
            }
        },
        autoCreateLotIdFunc : function(){
        	var inTrx, outTrx;
        	var wo_id = $.trim(controlsQuery.woIDSelect.val());
        	var tool_id = $.trim(controlsQuery.toolSelect.val());
        	if( !wo_id ){
        		showErrorDialog("","请选择内部订单号！"); 
        		return false;
        	}
			inTrx = {
				trx_id : "XPINQLOT",
				action_flg : "C",
				wo_id : wo_id,
				tool_id : tool_id,
				evt_usr : VAL.EVT_USER
			};
			outTrx = comTrxSubSendPostJson(inTrx);
			if (outTrx.rtn_code == "0000000") {
				controlsQuery.lotIdTxt.val(outTrx.lot_id);
			}
			return outTrx.lot_id;
        },
        wip_retain_func : function(){
        	var out_box_id,
        	    inObj,
        	    outObj,
        	    iary = [],
                tmpIary = {};

            out_box_id = controlsQuery.okOutCrrTxt.val();
            if( !out_box_id ){
                showErrorDialog("","请输入要转入的箱号！");
                clearOutBoxInput();
                return false;
            }
            
            tmpIary = {
            		box_id : out_box_id
                };
            iary.push(tmpIary);
                
            inObj = {
                    trx_id     : VAL.T_XPWIPRETAIN,
                    action_flg : "R",
                    evt_usr    : VAL.EVT_USER  ,
                    box_cnt    : 1        ,
                    iary       : iary
                };
            outObj = comTrxSubSendPostJson(inObj);
            if(outObj.rtn_code == VAL.NORMAL) {
            	showSuccessDialog("成功在制保留！");
            	return;
            }
        },
        wip_retain_cancel_func : function(){
        	var ope_id,ope_ver,ope_info,ope_info_ary,wo_id,tool_id;
        	
            wo_id = $.trim(controlsQuery.woIDSelect.val());
        	if( !wo_id ){
        		showErrorDialog("","请选择内部订单号！"); 
        		return false;
        	}
        	tool_id = $.trim(controlsQuery.toolSelect.val());
            ope_info = $.trim(controlsQuery.opeSelect.val());
            if(!ope_info){
                return false;
            }
            
            ope_info_ary = ope_info.split("@");
            ope_id = ope_info_ary[0];
            ope_ver = ope_info_ary[1];           
            if(!ope_id){
                return false;
            }
            if(!ope_ver){
                return false;
            }
        	
            $("#wip_retain_cancel_btn").showWipRetainCancelDialog({
                action_flg : "S",//"H" for hide,"S" for show
		        ope_id     : ope_id,
		        ope_ver    : ope_ver,
				wo_id      : wo_id,
				tool_id    : tool_id,
				user_id    : VAL.EVT_USER
              });
        }
        
    };

    function isArray(o){
        return Object.prototype.toString.call(o)=='[object Array]';
    }

    /**
     * Bind button click action
     */
    var iniButtonAction = function(){
        btnQuery.f1.click(function(){
            btnFunc.f1_func();
        });
        btnQuery.f2.click(function(){
            btnFunc.f2_func();
        });
        btnQuery.f6.click(function(){
            btnFunc.f6_func();
        });
        btnQuery.f8.click(function(){
            btnFunc.f8_func();
        });
        btnQuery.f9_cancel_unpack.click(function(){
            btnFunc.f9_cancel_unpack_func();
        });
        //在制保留
        btnQuery.wip_retain_btn.click(function(){
            btnFunc.wip_retain_func();
        });
        //取消在制保留
        btnQuery.wip_retain_cancel_btn.click(function(){
            btnFunc.wip_retain_cancel_func();
            resizeFnc();
        });
        
    };

    /**
     * grid  initialization
     */
    var iniGridInfo = function(){
        var grdInfoCM = [
            {name: 'mtrl_box_id_fk',index: 'mtrl_box_id_fk',label: PPBOX_ID_TAG       , width: BOX_ID_CLM},
            {name: 'slot_no',       index: 'slot_no',       label: SLOT_NO_TAG        , width: SLOT_NO_CLM},
            {name: 'prd_seq_id',    index: 'prd_seq_id',    label: PRD_SEQ_ID_TAG     , width: PRD_SEQ_ID_CLM , hidden:true},
            {name: 'fab_sn',        index: 'fab_sn',        label: PRD_SEQ_ID_TAG     , width: PRD_SEQ_ID_CLM},
            {name: 'judge',         index: 'judge',         label: JUDGE_TAG            , width: JUDGE_CLM}, //button
            {name: 'defect_detail', index: 'defect_detail', label: DEF_DTL_TAG           , width: DEFECT_DETAIL_CLM}, //button
            {name: 'th_judge_flg',  index: 'th_judge_flg',  label: '厚度'                 , width: TH_FZ_CLM,align:"center"},
            {name: 'fz_flg',        index: 'fz_flg',        label: '方阻'                 , width: TH_FZ_CLM,align:"center"},
            {name: 'evt_timestamp', index: 'evt_timestamp', label: EVT_TIMESTAMP         , width: TIMESTAMP_CLM},
            {name: 'evt_usr',       index: 'evt_usr',       label: EVT_USR               , width: USER_CLM},
            {name: 'box_id_fk',     index: 'box_id_fk',     label: MOVE_OUT_PPBOX_ID_TAG , width: BOX_ID_CLM},
            {name: 'sht_ope_msg',   index: 'sht_ope_msg',   label: '备注信息'               ,  width: SHT_OPE_MSG_CLM},
            {name: 'ds_recipe_id',  index: 'ds_recipe_id',  label: '来料备注'               ,  width: SHT_OPE_MSG_CLM},
            {name: 'group_id',      index: 'group_id',      label: '组代码'                ,  width: BOX_ID_CLM},
            {name: 'x_axis_cnt_fk', index: 'x_axis_cnt_fk', label: ''                    ,   width: 1 , hidden: true},
            {name: 'y_axis_cnt_fk', index: 'y_axis_cnt_fk', label: '', width: 1 , hidden: true},
            {name: 'mdl_id_fk',     index: 'mdl_id_fk',     label: '', width: 1 , hidden: true},
            {name: 'cr_tool_id_fk', index: 'cr_tool_id_fk', label: '', width: 1 , hidden: true},
            {name: 'cr_path_id_fk', index: 'cr_path_id_fk', label: '', width: 1 , hidden: true},
            {name: 'cr_path_ver_fk',index: 'cr_path_ver_fk',label: '', width: 1 , hidden: true},
            {name: 'cr_ope_no_fk',  index: 'cr_ope_no_fk',  label: '', width: 1 , hidden: true},
            {name: 'cr_ope_id_fk',  index: 'cr_ope_id_fk',  label: '', width: 1 , hidden: true},
            {name: 'cr_ope_ver_fk', index: 'cr_ope_ver_fk', label: '', width: 1 , hidden: true},
            {name: 'cr_proc_id_fk', index: 'cr_proc_id_fk', label: '', width: 1 , hidden: true},
            {name: 'wo_id_fk',      index: 'wo_id_fk',      label: '', width: 1 , hidden: true},
            {name: 'cus_id',        index: 'cus_id',      label: '', width: 80  , hidden: true}
        ];
        controlsQuery.mainGrd.grdId.jqGrid({
            url:"",
            datatype:"local",
            mtype:"POST",
            width:domObj.$releasedDetailDiv.width(),
            shrinkToFit:false,
            scroll:true,
            rownumWidth : true,
            resizable : true,
            rowNum:40,
            height:270,
            loadonce:true,
            fixed:true,
            viewrecords:true,
            multiselect : true,
            sortable:false,
            cmTemplate: {sortable:false},
            pager : controlsQuery.mainGrd.grdPgText,
            colModel: grdInfoCM
        });

        var grdInfoCMDef = [
            {name: 'defect_code',     index: 'defect_code',     label: DEF_CODE_TAG,      width: DEFECT_CODE_CLM,hidden:true},
            {name: 'defDsc',          index: 'defDsc',          label: DEF_DESC_TAG         },
            {name: 'defect_side',     index: 'defect_side',     label: DEF_LC_TAG         },
            {name: 'position',        index: 'position',        label: DEF_POSITION_TAG},
            {name: 'defect_cnt',      index: 'defect_cnt',      label: DEF_QTY_TAG}
        ];
        controlsQuery.defectDetailGrid.grdId.jqGrid({
            url:"",
            datatype:"local",
            mtype:"POST",
            width:domObj.$defectDetailDiv.width(),
            shrinkToFit:false,
            scroll:true,
            rownumWidth : true,
            resizable : true,
            rowNum:40,
            loadonce:true,
            fixed:true,
            viewrecords:true,
            pager : controlsQuery.defectDetailGrid.grdPgText,
            colModel: grdInfoCMDef
            
        });
        controlsQuery.mtrlBoxDetailGrid.grdId.jqGrid({
            url:"",
            datatype:"local",
            mtype:"POST",
            width:domObj.$mtrlBoxDetailDiv.width()*1.25,
            height:230,
            shrinkToFit:false,
            scroll:true,
            rownumbers  :true ,
            rowNum:20,
            rownumWidth : 20,
            loadonce:true,
            pager : '#mtrlBoxDetailPg',
            colModel:  [
                {name: 'prd_seq_id_fk'       , index: 'prd_seq_id_fk'           , label: '面板ID',       width: PRD_SEQ_ID_CLM},
                {name: 'ope_id_fk'           , index: 'ope_id_fk'               , label: '站点',         width: OPE_ID_FK_CLM,hidden:true },
                {name: 'ope_des'             , index: 'ope_des'                 , label: '站点',         width: OPE_ID_CLM},
                {name: 'data_num'            , index: 'data_num'                , label: '测点',         width: DATA_NUM_CLM , hidden:true },
                {name: 'data_num_cn'         , index: 'data_num_cn'             , label: '测点',         width: DATA_NUM_CLM },
                {name: 'data_value'          , index: 'data_value'              , label: '测点值',        width: DATA_NUM_CLM},
                {name: 'rpt_usr'             , index: 'rpt_usr'                 , label: '上报人',        width: RPT_USR_CLM },
                {name: 'rpt_timestamp'       , index: 'rpt_timestamp'           , label: '上报时间',      width: RPT_TIMESTAMP_CLM}
            ]
        });
    };

    var shortCutKeyBind = function(){
        document.onkeydown = function(event) {
            if(event.keyCode == F1_KEY){
                btnQuery.f1.click();
                return false;
            }else if (event.keyCode == F3_KEY) {
                btnQuery.f6.click();
                return false;
            }else if (event.keyCode == F12_KEY) {
                btnQuery.f8.click();
                return false;
            }else if (event.keyCode == F5_KEY) {
                btnQuery.f9_cancel_unpack.click();
                return false;
            }else if (event.keyCode == F7_KEY) {
                btnQuery.wip_retain_btn.click();
                return false;
            }else if (event.keyCode == F8_KEY) {
                btnQuery.wip_retain_cancel_btn.click();
                return false;
            }

            return true;
        };
    };

    /**
     * Other action bind
     */
    var otherActionBind = function(){
        //Stop from auto commit
        $("form").submit(function(e){
            return false;
        });
        
        $("#ppboxIdTxt,#slotIDTxt,#lotIdTxt").keydown(function(event){
			if (event.keyCode == 13) {
				return false;
			}
        });
        
      //  controlsQuery.okOutCrrTxt.attr({"disabled":true});

        //Ope select change ==> tool auto refresh & defect auto refresh
        controlsQuery.opeSelect.change(function(){
            toolFunc.iniToolSelect();
            btnQuery.f1.click();
        });
        controlsQuery.woTypeSelect.change(function(){
           btnQuery.f1.click();
        });
        //OK/NG/I button click action
//        controlsQuery.okOutCrrTxt[0].disabled = false;
//         btnQuery.okOutBtn.click(function (){
//    		controlsQuery.okOutCrrTxt.attr({"disabled":false});
//    		
//    		controlsQuery.okOutCrrTxt.val("");
//    		
//    		controlsQuery.okOutCrrTxt.focus();
//         	toolFunc.crrInputKeyDownFnc(controlsQuery.okOutCrrTxt);
//             oneKeyTimeArr = [];
//             showErrorDialog("","请扫码输入箱号");
//             controlsQuery.okOutCrrTxt.val("");
//         });

        // btnQuery.okOutBtn.click(clearOutBoxInput);


        controlsQuery.woIDSelect.change(function(){
            toolFunc.woIDSelectChangeFnc();
        });

        //Layout select
        controlsQuery.layoutIdSelect.change(function(){
            toolFunc.syncLayoutInfo();
        });

        //Auto query when press enter after keyin prdID
        controlsQuery.prdIDTxt.keydown(function(event){
            $(this).val($(this).val().toUpperCase());
            if(event.keyCode === 13){
                btnQuery.f6.click();
                return false;
            }
        });


        shortCutKeyBind();
        
        controlsQuery.mainGrd.grdId.on("click","button.thCss",function (){
    		var rowId =  $(this).closest("tr")[0].id;
    		console.info(rowId);
    		var spcDialog = new SpcDialog();
    		if(!spcDialog.showDialogFnc(rowId,"CDPC")){
    			return false;
    		}

    		var divWidth = $("#spcDialog").width() - $("#dataItemEditDiv").width();
    		$("#spcDiv").width(divWidth - 80);
    		$("#spcDialog_woGrd").setGridWidth(divWidth - 85);
    		return false;
    	});
    	controlsQuery.mainGrd.grdId.on("click","button.fzCss",function (){
    		var rowId =  $(this).closest("tr")[0].id;
    		console.info(rowId);
    		var spcDialog = new SpcDialog();
    		if(!spcDialog.showDialogFnc(rowId,"CZPC")){
        			return false;
    		}
    		
    		var divWidth = $("#spcDialog").width() - $("#dataItemEditDiv").width();
    		$("#spcDiv").width(divWidth - 80);
    		$("#spcDialog_woGrd").setGridWidth(divWidth - 85);
    		
    		return false;
    	});
    };

    /**
     * 厚度判定和阻值判定dialog
     * author：THY
     */
    var SpcDialog = function(){
    	var Val = {
    		rowId : "",
    		mes_id : "",
    		mes_id_act : ""
    	};
        this.showDialogFnc  = function(rowId,mes_id){
        	Val.rowId = rowId;
        	Val.mes_id = mes_id;
        	
        	mainGrd = controlsQuery.mainGrd.grdId;
            rowData = mainGrd.jqGrid("getRowData",rowId);
            prd_seq_id = rowData.prd_seq_id;
            $("#prd_seq_id").val(prd_seq_id);
            if(""===prd_seq_id){
            	return false;
            }
            var iary,
                inTrx,
                outTrx;
            inTrx = {
                trx_id     : VAL.T_XPSPCRET ,
                action_flg : 'Q'        ,
                prd_seq_id_fk :  prd_seq_id,
                mes_id : mes_id,
                proc_id : rowData.cr_proc_id_fk
            };
            outTrx = comTrxSubSendPostJson(inTrx);
            var oary;
            if (outTrx.rtn_code==VAL.NORMAL){
            	if(!this.queryFnc(rowId,mes_id)){
            		return false;
            	}
            	this.initialDialogFnc(rowId,mes_id);
                
                
                $("#spcDialog_woGrd").jqGrid("clearGridData");
                outTrx.data_cnt == "1" ? outTrx.oary[0] = outTrx.oary : outTrx.oary;
                for(var i=0;i<outTrx.data_cnt;i++){
                	outTrx.oary[i].data_num_cn = outTrx.oary[i].data_num.replace('T','测点');
                }
                setGridInfo(outTrx.oary,"#spcDialog_woGrd");
                $("#ope_id").val(outTrx.ope_dsc);
            }

        };
       
        this.queryFnc = function (rowId,mes_id) {
        	
        	mainGrd = controlsQuery.mainGrd.grdId;
            rowData = mainGrd.jqGrid("getRowData",rowId);
            prd_seq_id = rowData.prd_seq_id;

			var iary1 = {
				tool_id_fk : rowData.cr_tool_id_fk,
				ope_no : rowData.cr_ope_no_fk,
				mes_id_fk : mes_id,
				rep_unit : 'P',
				data_pat : '00' 
			};
			var inTrxObj1 = {
				trx_id : 'XPMLITEM',
				action_flg : 'Q',
				wo_id_fk : $.trim(controlsQuery.woIDSelect.val()),
				iaryA : iary1
			};
			var outTrxObj1 = comTrxSubSendPostJson(inTrxObj1);
			$("#dataItemEditDiv").empty();
			if (outTrxObj1.rtn_code == VAL.NORMAL) {
				var tbl_cnt = outTrxObj1.tbl_cnt_b;
				if(tbl_cnt<=0){
					showErrorDialog("", "机台"+rowData.cr_tool_id_fk+",MES_ID["+mes_id + "] 没有设定机台量测项目");
					return false;
				}

             /*   var thicknessEntity,thicknessType;
                var usl,lsl;
                if(mes_id === "CDPC"){
                    thicknessEntity = spcThicknessRule.getThicknessEntity(rowData.cr_ope_id_fk,rowData.wo_id_fk);
                    if(thicknessEntity.thickness_type == spcThicknessRule.OTHER_THICKNESS){
                        return false;
                    }
                    thicknessType = thicknessEntity.thickness_type;
                }

                var inObj = {
                    trx_id : "XPCHKOOS",
                    mes_id : mes_id,
                    mdl_id : rowData.mdl_id_fk,
                    wo_id  : rowData.wo_id_fk,
                    path_id : rowData.cr_path_id_fk,
                    ope_id  : rowData.cr_ope_id_fk
                };
                if(thicknessType){
                    inObj.thickness_type = thicknessType;
                }
                outObj = comTrxSubSendPostJson(inObj);
                if(outObj.rtn_code === VAL.NORMAL){
                    if(outObj.tbl_cnt ==1){
                        var oary = outObj.oary;
                        usl = parseFloat(oary.usl).toFixed(3);
                        lsl = parseFloat(oary.lsl).toFixed(3);
                        $("#spcDialog_uslTxt").val(usl);
                        $("#spcDialog_lslTxt").val(lsl);
                        $("#spcDialog_alarmMessageTxt").val(oary.alarm_message);
                    }else{
                        $("#spcDialog_uslTxt").val("");
                        $("#spcDialog_lslTxt").val("");
                        $("#spcDialog_alarmMessageTxt").val("");
                    }

                }
*/
				var str = '<table id="dataItemTbl" class="table table-striped table-bordered table-condensed" >'
					    + '<thead><tr>'
						+ '<th class="Header_Text " >参数序号 </th>'
						+ '<th class="Header_Text " >参数名称 </th>'
						+ '<th class="Header_Text " >组内序号 </th>'
						+ '<th class="Header_Text " >参数说明 </th>'
						+ '<th class="Header_Text " >值 </th>'
						+ '<th class="Header_Text " >下限 </th>'
						+ '<th class="Header_Text " >上限</th></tr></thead><tbody> ';
				for (var i = 0; i < tbl_cnt; i++) {
					str = str + "<tr>" + '<td class=" dataItemTdCss">'
							+ outTrxObj1.oaryB[i].data_id + "</td>"
							+ '<td id ="tbl_data_group' + i
							+ '\" class=" dataItemTdCss">'
							+ outTrxObj1.oaryB[i].data_group + "</td>"
							+ '<td id ="tbl_data_group_seq' + i
							+ '\" class=" dataItemTdCss">'
							+ outTrxObj1.oaryB[i].data_group_seq + "</td>"
							+ '<td class=" dataItemTdCss">'
							+ outTrxObj1.oaryB[i].data_dsc + "</td>"
							+ '<td class=" dataItemTdCss">'
							+ '<input type="text" name='+ i +' class ="span2 numberCssA" id="dataItem_'
							+ i + '_Txt\" />' + "</td>";
					if(outTrxObj1.oaryB[i].l_spec){
						str = str + '<td class=" dataItemTdCss"'+'id="lsl_'+i +'" >'
						+ outTrxObj1.oaryB[i].l_spec + "</td>";
					}
					if(outTrxObj1.oaryB[i].u_spec){
						str = str + '<td class=" dataItemTdCss"'+'id="usl_'+i+ '" >'
						+ outTrxObj1.oaryB[i].u_spec + "</td>";
					}	
					str = str + "</tr>";
				}
				str = str + "</tbody></table>";
				$(str).appendTo("#dataItemEditDiv");
				for (var i = 0; i < tbl_cnt; i++) {
				$("#dataItem_" + i + "_Txt").keypress(function(event){
						if (event.keyCode == 13) {
							var nextSelecter,uslSelector,lslSelector,usl,lsl,index,value;
				    		index = this.id.split("_")[1];
				    		uslSelector = "#usl_"+index ;
				    		usl = parseFloat($(uslSelector).text());
				    		lslSelector = "#lsl_"+index;
				    		lsl = parseFloat($(lslSelector).text());
				    		value = parseFloat($(this).val()); 
				    		if(value>usl){
				    			showMessengerErrorDialog("输入数值高于标准上限"+usl,2);
				    			$(this).focus();
				    			return false;
				    		}else if(value<lsl){
				    			showMessengerErrorDialog("输入数值低于标准下限"+lsl,2);
				    			$(this).focus();
				    			return false;
				    		}
				    		nextSelecter = "#dataItem_" +( parseInt(this.name,10)+1 ) + "_Txt";
				    		$(nextSelecter).focus();
						}
					});
				}
				showMessengerSuccessDialog("刷新列表成功!!",1);
				
				$(".numberCssA").blur(function() {
					var $this = $(this);
					var val = $this.val().trim();
					if (val && !ComRegex.isNumber(val)) {
						showErrorDialog("", "[" + val + "]不是一个有效的数字,错误");
						$this.val("");
					}
				});
			}
			return true;
    	};
        
    	
        this.initialDialogFnc = function(rowId,mes_id){
            $('#spcDialog').modal({
                backdrop:true,
                keyboard:false,
                show:false
            });
            $('#spcDialog').unbind('shown.bs.modal');
            $("#spcDialog_reportBtn").unbind('click');
            
            $('#spcDialog').modal("show");
            $("#spcDialog_reportBtn").bind('click',this.reportFnc);
            $("#spcDialog_woGrd").jqGrid({
                url:"",
                datatype:"local",
                mtype:"POST",
                autowidth:true,//宽度根据父元素自适应
                height:300,
                shrinkToFit:false,
                scroll:true,
                rownumbers  :true ,
                rowNum:20,
                rownumWidth : 20,
                loadonce:true,
                pager : '#spcDialog_woPg',
                colModel:  [
                    {name: 'prd_seq_id_fk'       , index: 'prd_seq_id_fk'           , label: '面板ID',       width: PRD_SEQ_ID_CLM},
                    {name: 'ope_id_fk'           , index: 'ope_id_fk'               , label: '站点',         width: OPE_ID_FK_CLM,hidden:true },
                    {name: 'ope_des'             , index: 'ope_des'                 , label: '站点',         width: OPE_ID_CLM},
                    {name: 'data_num'            , index: 'data_num'                , label: '测点',         width: DATA_NUM_CLM , hidden:true },
                    {name: 'data_num_cn'         , index: 'data_num_cn'             , label: '测点',         width: DATA_NUM_CLM },
                    {name: 'data_value'          , index: 'data_value'              , label: '测点值',        width: DATA_NUM_CLM},
                    {name: 'rpt_usr'             , index: 'rpt_usr'                 , label: '上报人',        width: RPT_USR_CLM },
                    {name: 'rpt_timestamp'       , index: 'rpt_timestamp'           , label: '上报时间',      width: RPT_TIMESTAMP_CLM}
                ]
            });
        };
        
        this.reportFnc = function (){
        	mainGrd = controlsQuery.mainGrd.grdId;
            rowData = mainGrd.jqGrid("getRowData",Val.rowId);
            
    		prd_seq_id = rowData.prd_seq_id;
    		cus_id = rowData.cus_id;
    		var judgeStr = "OK";
    		
    		var tableItemCnt = 0;
    		tableItemCnt = $("#dataItemTbl tr").length - 1;
    		var iaryAry = new Array();
    		for (var i = 0; i < tableItemCnt; i++) {
    			if ($("#dataItem_" + i + "_Txt").val() != "") {
    				var iary = {
    					data_group : $("#tbl_data_group" + i).text(),
    					data_value : $("#dataItem_" + i + "_Txt").val().trim(),
    					data_group_seq : $("#tbl_data_group_seq" + i).text()
    				};
    				iaryAry.push(iary);
    				if (judgeStr != "NG"){
    					if(($("#dataItem_" + i + "_Txt").val()) < ($("#lsl_"+i ).text()) || ($("#dataItem_" + i + "_Txt").val()) > ($("#usl_"+i ).text())){
    						judgeStr = "NG";
    					}else {
    						judgeStr = "OK";
    					}
    				}
    			}
    		}
    		
    		// Send Tx
    		var inTrxObj = {
    			trx_id : 'XPCMSRDT',
    			prd_seq_id : prd_seq_id,
    			tool_id : $("#toolSelect").find("option:selected").text(),
    			data_pat_fk : '00',
    			mes_id_fk : Val.mes_id,
    			path_id : rowData.cr_path_id_fk,
    			path_ver : rowData.cr_path_ver_fk,
    			ope_no : rowData.cr_ope_no_fk,
    			ope_id : rowData.cr_ope_id_fk,
    			ope_ver : rowData.cr_ope_ver_fk,
    			proc_id : rowData.cr_proc_id_fk,
    			rpt_usr : $("#userId").text(),
    			judgeStr : judgeStr,
    			data_cnt : iaryAry.length,
    			iary : iaryAry

    		};
    		var lotId = controlsQuery.lotIdTxt.val(); 
    		if(lotId){
    			inTrxObj.lot_id = lotId;
    		}
    		spcThicknessRule.reportSPC(inTrxObj,Val.mes_id,rowData.cr_ope_id_fk,rowData.wo_id_fk,controlsQuery.lotIdTxt.val(),function(outTrxObj){
    			if (outTrxObj.rtn_code == VAL.NORMAL) {
	    			showMessengerSuccessDialog("数据上报成功!!",1);
	    			$("[id^='dataItem_']").val("");
	                $('#spcDialog').modal("hide");
	                controlsQuery.prdIDTxt.focus();
	    			return false;
	    		}
    		})
    		
    		if(cus_id=="068"&&judgeStr=="NG"){
    			$("#spcDialog_reportBtn").showCallBackWarnningDialog({
					errMsg : "玻璃: ["+prd_seq_id+"]厚度超标，请取消释放",
					callbackFn : function(data) {
						if (data.result == true) {
					        var prd_seq_id,
			                inObj,
			                outObj,
			                selectRow;

			                selectRow = controlsQuery.mainGrd.grdId.jqGrid("getRowData", Val.rowId);
			                prd_seq_id = selectRow['prd_seq_id'];

			                inObj = {
			                    trx_id         : VAL.T_XPUNPACK     ,
			                    action_flg     : "C"                ,
			                    prd_seq_id     : prd_seq_id         ,
			                    evt_usr        : VAL.EVT_USER
			                };
			                outObj = comTrxSubSendPostJson(inObj);
			                if (outObj.rtn_code == VAL.NORMAL) {
			                    controlsQuery.mainGrd.grdId.jqGrid('delRowData', Val.rowId);
			                    controlsQuery.to_thicknessTxt.val(outObj.to_thickness);
			                }else{
			                    return false;
			                }
				        }else {
				        	return false;
				        }						
					}	        		
	        	});
    		}
        };
    };
    
    /**
     * Ini contorl's data
     */
    var iniContorlData = function(){
        toolFunc.clearInput();

        //Tool info
        toolFunc.iniOpeSelect();
        toolFunc.iniToolSelect();
      //Wo info
        toolFunc.iniWoTypeSelect();
        btnQuery.f1.click();
        
        //Ini defect info
        toolFunc.get_all_defect_func();

    };

    /**
     * Ini view, data and action bind
     */
    var initializationFunc = function(){
        iniGridInfo();
        iniButtonAction();
        otherActionBind();
        iniContorlData();
        toolFunc.setDestShopSel();
    };

    initializationFunc();
    
    function resizeFnc(){ 
    	comResize(controlsQuery.W,controlsQuery.mainGrd.fatherDiv,controlsQuery.mainGrd.grdId);
		comResize(controlsQuery.W,controlsQuery.defectDetailGrid.fatherDiv,controlsQuery.defectDetailGrid.grdId);
		$("#defectDetailGrd").setGridWidth((controlsQuery.W.width()-controlsQuery.defectDetailGrid.grdId.offset().left)*0.95);
		
		var dialogHeight = $("#wip_retain_Dialog").height(); 
		$("#modalBodyDiv").width(domObj.$window.width()*0.85);
		domObj.$retainBoxInfoDiv.width(domObj.$window.width() * 0.25);
		var divWidth = domObj.$retainBoxInfoDiv.width();                                   
		domObj.$retainBoxInfoDiv.height(dialogHeight * 0.6);                          
		domObj.$wipRetainInfoGrd.setGridWidth(divWidth * 0.99);                   
		domObj.$wipRetainInfoGrd.setGridHeight(dialogHeight * 0.6 - 100);   
		
		domObj.$wipRetainDetailInfoDiv.width(domObj.$window.width() * 0.40); 
		divWidth = domObj.$wipRetainDetailInfoDiv.width();   
		domObj.$wipRetainDetailInfoDiv.height(dialogHeight * 0.6);                          
		domObj.$wipRetainDetailInfoGrd.setGridWidth(divWidth * 1.08);                   
		domObj.$wipRetainDetailInfoGrd.setGridHeight(dialogHeight * 0.6 - 100);
		
		divWidth = $("#spcDialog").width() - $("#dataItemEditDiv").width();
		$("#spcDiv").width(divWidth - 80);
		$("#spcDialog_woGrd").setGridWidth(divWidth - 85);
		
		offsetBottom = $("#spcDialogDiv").height();
		$("#spcDiv").height(offsetBottom - 10);
		$("#spcDialog_woGrd").setGridHeight(offsetBottom - 15);
    };  
    $("#inputInfoSpan4Div").height($("#inputInfoSpan4Div").height() * 0.9);
   // resizeFnc();
//    controlsQuery.W.resize(function() {
//    	resizeFnc();
//	});
//
//强制扫码输入箱号
    var oneKeyTime; /* 一次按键时间间隔 */
    var twoKeyTime; /* 两次按键时间间隔 */
    var keyDownTime; /* 键按下的时间    */
    var spanTime = 70; /* 一次按键按下到释放的时间间隔 */
    var oneKeyTimeArr = [];
    // var isScanner = false;
    var isScanner = true;
    controlsQuery.okOutCrrTxt.keydown(function(e){
        var d = new Date();
        var curTime = parseInt(d.getTime());
        if(keyDownTime !== '' && keyDownTime !== NaN){
            twoKeyTime = curTime - keyDownTime;
        }
        keyDownTime = curTime;
        // console.log("keyDownTime:"+keyDownTime);
	});
    controlsQuery.okOutCrrTxt.keyup(function (e) {
        var d = new Date();
        var keyUpTime = d.getTime();
        oneKeyTime = parseInt(keyUpTime) - parseInt(keyDownTime);
        oneKeyTimeArr.push(oneKeyTime);
        // console.log("oneKeyTime:"+oneKeyTime);
    });
    controlsQuery.okOutCrrTxt.keypress(function (e) {
        if(e.keyCode==13){
            console.log(oneKeyTimeArr);
            var mean = meanFunc(oneKeyTimeArr);
            console.log("meanTime:" + mean);
            if(mean>spanTime){
                isScanner = false;
                console.log("禁止手动输入");
                clearOutBoxInput();
                showErrorDialog("","请扫码输入箱号");
            }else{
                isScanner = true;
                $("#okOutCrrTxt").attr("readonly","readonly");
                console.log("执行查找箱子");
                toolFunc.crrInputKeyDownFnc(controlsQuery.okOutCrrTxt);
            }
            oneKeyTimeArr = [];
        }
    });
    function meanFunc(arr) {
        var sum = 0;
        for(var i=0;i<arr.length;i++){
            sum += arr[i];
        }
        var mean = sum/arr.length;
        return mean;
    }
    function clearOutBoxInput() {
        console.log("清空出账箱号输入框");
        controlsQuery.okOutCrrTxt.removeAttr("readonly");
        controlsQuery.okOutCrrTxt.val("");
        controlsQuery.okOutCrrTxt.focus();
        isScanner = false;
    }
});
